Promise.all 不适用于一系列异步函数

Max*_*Max 4 javascript promise ecmascript-6 es6-promise

考虑以下代码,理论上在 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);
Run Code Online (Sandbox Code Playgroud)

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


但是,如果我将异步函数包装在 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);
Run Code Online (Sandbox Code Playgroud)

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

Ber*_*rgi 7

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);
Run Code Online (Sandbox Code Playgroud)

或者

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

await Promise.all(promiseArray);
Run Code Online (Sandbox Code Playgroud)