Sunday, May 12, 2024
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

 Answers
6

Promise.all takes an array of promises as its argument, not an array of async functions. Also you were missing a return statement. You should write


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

await Promise.all(promiseArray);

or


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

await Promise.all(promiseArray);

[#3067] Friday, July 24, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emiliano

Total Points: 381
Total Questions: 109
Total Answers: 93

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
emiliano questions
;