[英]Promise.all not working with an array of async functions
理論上,考慮以下代碼,它在 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);
我不知道為什么,但它不起作用。 控制台上沒有打印任何內容。
但是,如果我將異步 function 包裝在 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
將一組承諾作為其參數,而不是一組async function
s。 此外,您還缺少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);
Its normal Promise.all take an array of Promises, async function are of type function, but returns a Promise once invoked if no explicite return it will return a resolved promise with undefined value.
async function myAsyncFunction(){ return 1; } console.log(typeof myAsyncFunction) console.log(typeof myAsyncFunction()) console.log(myAsyncFunction() instanceof Promise)
您從 map 回調返回 function,而不是 promise。 而是返回foo(num)
。 然后在展平之后你有一系列的承諾。
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));
異步function 必須返回 promise。 您的第一個實現需要一個 return 語句:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.