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