Sub topic 14
Awaiting Inside Loops: Sequential vs Concurrent Work
This chapter assumes you know for...of and array methods such as map from the earlier chapters. You should also be comfortable with promises and async/await: an async function returns a promise, and await pauses that function until a promise settles.
When a loop body contains asynchronous work, you have to decide something a plain loop never makes you decide. Should each task wait for the one before it, or should all tasks start at once? The two choices give the same results, but they take very different amounts of time.
Sequential: await inside for...of
If you put await inside a for...of loop, the loop pauses on every iteration. The next task does not start until the current one finishes.
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
async function sequential() {
console.time("sequential");
for (const ms of [30, 10]) {
console.log(await delay(ms)); // 30, then 10
}
console.timeEnd("sequential"); // about 40ms
}
sequential();The total time is the sum of the delays. Sequential order is the right choice when one step depends on the result of the step before it. It is also right when you must limit load on a server or keep side effects, such as database writes, in order.
Concurrent: Promise.all with map
When the tasks are independent, start them all together. map calls delay for every item right away and produces an array of pending promises. Promise.all then waits for all of them.
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
async function concurrent() {
console.time("concurrent");
const results = await Promise.all([30, 10].map(delay));
console.log(results); // [30, 10]
console.timeEnd("concurrent"); // about 30ms
}
concurrent();The total time is roughly the slowest task. The results stay in input order, not in the order the tasks finish. If any promise rejects, Promise.all rejects immediately. Use Promise.allSettled if you want every outcome, including the failures.
The forEach trap
forEach ignores the return value of its callback. If the callback is async, the promises it returns are thrown away, and nothing waits for them.
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
function broken() {
[30, 10].forEach(async (ms) => {
console.log(await delay(ms));
});
console.log("done");
}
broken();
// "done", then 10, then 30The code prints "done" first, and the tasks finish in whatever order they complete. If you need sequential order, use for...of. If you need concurrency, use Promise.all with map.
for await...of
for await...of loops over an async iterable, which is a source that produces its values over time. Async generators (async function*) and many streams are async iterables. Each iteration waits for the next value before the loop body runs.
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
async function* countdown(n) {
while (n > 0) {
await delay(10);
yield n--;
}
}
async function run() {
for await (const value of countdown(3)) {
console.log(value); // 3, 2, 1
}
}
run();for await...of also accepts an ordinary array of promises and awaits each one in order. With an array, though, all the promises already started when the array was built. Promise.all handles that case more clearly.
| Goal | Construct |
|---|---|
| Steps depend on each other or must run in order | `await` inside `for...of` |
| Independent tasks, fastest total time | `Promise.all(items.map(fn))` |
| Need every result, even the failures | `Promise.allSettled` |
| Values arrive over time from a stream or generator | `for await...of` |
Exercise
A function fetches three independent URLs that take 100ms, 200ms, and 300ms. About how long does it take with await inside for...of, and how long with Promise.all and map?
Show answer
With for...of it takes about 600ms, because the delays add up. With Promise.all it takes about 300ms, because the requests overlap and the total equals the slowest one.
Exercise
Why does await items.forEach(async (x) => save(x)) not wait for the saves to finish, and how would you fix it so all saves run concurrently?
Show answer
forEach discards the promises its callback returns and itself returns undefined, so there is nothing to await. Use await Promise.all(items.map((x) => save(x))).