使用
.map()
和 Promise.all()
使用这两个代码片段来并行解决承诺。
片段1:
const myArray = [1, 2, 3, 4];
const asyncTask = (name) => {
return new Promise((resolve) => setTimeout(() => {
const result = `resolved: ${name}`
console.log({ result })
resolve(result)
}, 1000));
};
(async () => {
console.log('start');
const promises = myArray.map((value) => {
return asyncTask(`task-${value}`);
});
await Promise.all(promises);
console.log('end');
})();
片段2:
const myArray = [1, 2, 3, 4];
const asyncTask = (name) => {
return new Promise((resolve) => setTimeout(() => {
const result = `resolved: ${name}`
console.log({ result })
resolve(result)
}, 1000));
};
(async () => {
console.log('start');
const promises = myArray.map(async (value) => {
await asyncTask(`task-${value}`);
});
await Promise.all(promises);
console.log('end');
})();
两个片段做的完全一样。我的理解是片段 2 将 not 等待任何事情,因为
.map()
中的回调是 lacking a return statement 因此 promises
将是 Promise<void>[]
类型。结果 await Promise.all(promises)
仍然等待回调的所有承诺,而不是立即解决。这是为什么?
尝试了上述代码的许多不同变体。我希望片段 2 不是
await
但立即解决记录以下内容:
> 'start'
> 'end'
> *result of promises*
而不是(实际):
> 'start'
> *result of promises*
> 'end'
缺少
return
语句意味着该函数在函数末尾执行隐式 return undefined
。
async
它返回一个 Promise<undefined>
但是这个 Promise 只在函数完成时解析;延迟await asyncTask...
.
const myArray = [1, 2, 3, 4];
const asyncTask = (name) => {
return new Promise((resolve) => setTimeout(() => {
const result = `resolved: ${name}`
console.log({ result })
resolve(result)
}, 1000));
};
(async () => {
console.log('start');
const promises = myArray.map(async (value) => {
/* removed await */ asyncTask(`task-${value}`);
});
await Promise.all(promises);
console.log('end');
})();