Your first problem: The output array is empty because you use it before any of promises is executes. You have to await
all promises before using the array.
The second problem: Promises can execute and therefore push
items in (pseudo-)random order. Your output array can get shuffled.
The solution is (1) await
all promises and (2) keep order of them (using Array.prototype.map
):
async function foo(input) {
let output = await Promise.all(input.map(async element => {
return element * 2;
}));
return output;
}
// Call it
let input = [ 1, 2, 3, 4, ]; // This is your input array
foo(input).then(output => console.log(output));
The Promises.all
is async
function that takes array of promises and returns array of their results.
Array.prototype.map
executes function for each item of the array.
More information: