Reputation: 2993
async function processArray(array) {
let myOrderedArray = [];
for (const item of array) {
const value = await getValue(item);
myOrderedArray.push(value);
}
return myOrderedArray;
}
I want to go through the array, for each item perform an async operation, and then save the value I get back in a different array. This results array is ordered: I want the result value for item1
appear in the result at position 1, before item2
, and so on.
However, these are async calls. I cannot be sure that my async function calls return in the exact same order, since they're, well, not synchronous. How can I achieve something like this?
Upvotes: 1
Views: 893
Reputation: 7770
Since you are awaiting the getValue
function, the sequence will be maintained although it is asynchronous call. The push function will not be called till the time first call is successful. for...of
loop respects the asynchrouns promise code.
Upvotes: 2
Reputation: 85132
Your code already guarantees they'll be in order, but it does it in a slow way. Your code will run until the first await and then block until it gets the value. Only once it has the first value will it loop, and then block again for the second value.
If you want to do them all in parallel, then you'll want to create an array of promises, and use Promise.all to wait for them all to finish.
async function processArray(array) {
const promises = array.map(item => getValue(item));
const myOrderedArray = await Promise.all(promises);
return myOrderedArray;
}
If you're not doing anything with myOrderedArray inside process array, then you can simplify this to:
function processArray(array) {
const promises = array.map(item => getValue(item));
return Promise.all(promises);
}
Upvotes: 1
Reputation: 124
async function processArray(array) {
return array.map(async item => {
return await getValue(item);
})
}
promise in promises is ordered
Upvotes: 0