Promise.all不适用于异步函数数组



理论上,考虑以下代码,这些代码在I/O操作完成后将消息打印到控制台。

const foo = (num) => new Promise(resolve => setTimeout(resolve, num * 1000)); // An async I/O function in actual code
array = [[1, 2, 3], [1, 2, 3] , [1, 2, 3]];
const promiseArray = array.map(arr => {
arr.map(num => {
return (async () => {
await foo(num);
console.log(num);
});
});
}).flat();
await Promise.all(promiseArray);

我不知道为什么,但它不起作用。控制台上没有打印任何内容。


然而,如果我将异步函数封装在Promise构造函数中,它会起作用

const foo = (num) => new Promise(resolve => setTimeout(resolve, num * 1000)); // An async I/O function in actual code
array = [[1, 2, 3], [1, 2, 3] , [1, 2, 3]];
const promiseArray = array.map(arr => {
arr.map(num => {
return new Promise(async () => {
await foo(num);
console.log(num);
});
});
}).flat();
await Promise.all(promiseArray);

我应该如何重写代码以摆脱Promise构造函数?

Promise.all采用promise数组作为参数,而不是async functions数组。此外,您还缺少return语句。你应该写

const promiseArray = array.flatMap(arr => {
return arr.map(async num => {
await foo(num);
console.log(num);
});
});
await Promise.all(promiseArray);

const promiseArray = array.map(async arr => {
await Promise.all(arr.map(async num => {
await foo(num);
console.log(num);
}));
});
await Promise.all(promiseArray);

它的普通Promise.all接受一个Promises数组,异步函数属于函数类型,但一旦调用,就会返回一个Promise。如果没有显式返回,它将返回一个具有未定义值的已解析Promise。

async function myAsyncFunction(){
return 1; 
}
console.log(typeof myAsyncFunction)
console.log(typeof myAsyncFunction())
console.log(myAsyncFunction() instanceof Promise)

您从映射回调返回的是一个函数,而不是promise。而是返回CCD_ 4。扁平化之后,你会得到一系列的承诺。

const foo = (num) => new Promise(resolve => setTimeout(resolve, num * 1000)); // An async I/O function in actual code
array = [[1, 2, 3], [1, 2, 3] , [1, 2, 3]];
const promiseArray = array.map(arr => {
return arr.map(foo); // its equal arr.map(num => foo(num));
}).flat();
const results = await Promise.all(promiseArray);
results.forEach(item => console.log(item));

async函数必须返回promise。您的第一个实现需要返回语句:

const array = [[1, 2, 3], [1, 2, 3] , [1, 2, 3]];
const promiseArray = array.map(arr => {
// returning the mapped list
return arr.map(async (num) => {
const result = await foo(num);
console.log('Num: ' + num);
// return at the end of async will generate a promise fulfillment for you.
// see: https://developers.google.com/web/fundamentals/primers/async-functions
return result;
});
}).flat();
const result = await Promise.all(promiseArray);
console.log('result: ' + result);

最新更新