142
rated 0 times
[
149]
[
7]
/ answers: 1 / hits: 9471
/ 4 Years ago, sun, july 26, 2020, 12:00:00
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?
More From » ecmascript-6