Consider the following code which print messages to console after I/O operations complete, in theory.
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);
I don't know why but it doesn't work. Nothing was printed to the console.
However it would work if I wrap the async function within a Promise constructor
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);
How should I rewrite the code to get rid of the Promise constructor?
promiseArrayis just[undefined, undefined, undefined]. 2. Even if you put areturn, you aren't returning promises but an array of async functions. You have to execute them to get promises.