Promise.all 不使用异步函数数组

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);

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


但是,如果我将异步函数包装在 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 构造函数?

您正在 return 从地图回调中调用函数,而不是承诺。而是 return 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));

一个异步函数必须return一个承诺。您的第一个实现需要 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);

Promise.all 将一组 promises 作为其参数,而不是一组 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 接受一个 Promise 数组,异步函数是函数类型,但是 return 一个 Promise 一旦被调用,如果没有明确 return 它会 return具有未定义值的已解决承诺。

async function myAsyncFunction(){
  return 1; 
}

console.log(typeof myAsyncFunction)
console.log(typeof myAsyncFunction())
console.log(myAsyncFunction() instanceof Promise)