Basic async and await is simple.
Things get a bit more complicated when you try to use await in loops.
Let's discuss further about in this article.
Prerequisite:
I’m going to assume you know how to use async and await. If you don’t, you can check it out here
Await in a for loop
for (let index = 0; index < iterable.length; index++) {
const value = await remoteApiCall();
}
for await (const variable of iterable) {
const value = await remoteApiCall();
}
When you use await, you expect JavaScript to pause execution until the awaited promise gets resolved. This means awaits in a for-loop gets executed in series.
Same behaviour with while
& for-of
loops, i.e. all awaits gets executed in series one after another.
Loops that require a callback
await won’t work with loops that require a callback. Examples of such loops that require a callback i.e.
- forEach
- map
- filter
- reduce
Using await in loops with a callback
...
console.log('start')
const promises = iterable.map(remoteApiCall)
const values = await Promise.all(promises) // using promise.all is key
console.log(values)
console.log('end')
The console logs are printed in order.
Summary
-
await
doesn't work with loop in callback in serial fashion. - The solution is to use
await Promise.all(...)
where you pass all the promises
Top comments (1)
very interesting ! did not know this about Promise.All ... at.all
from MDN: developer.mozilla.org/en-US/docs/W...
"Returned values will be in order of the Promises passed, regardless of completion order."