不要等待结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function delay() {
return new Promise(resolve=> setTimeout(resolve, 3000));
}
async function delayedLog(item) {
await delay();
console.log(item);
}
async function processArray(array) {
array.forEach(async (item) => {
await delayedLog(item)
})
console.log('Done');
}
processArray([1,2,3]);
// Done!
// 1
// 2
// 3

串行遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function delay() {
return new Promise(resolve=> setTimeout(resolve, 3000));
}
async function delayedLog(item) {
await delay();
console.log(item);
}
async function processArray(array) {
for (const item of array) {
await delayedLog(item)
}
console.log('Done');
}
processArray([1,2,3]);
// 1
// 2
// 3
// Done!

并行遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
function delay() {
return new Promise(resolve=> setTimeout(resolve, 3000));
}
async function delayedLog(item) {
await delay();
console.log(item);
}
async function processArray(array) {
const promisees = array.map(delayedLog)
await Promise.all(promisees)
console.log('Done');
}
processArray([1,2,3]);