Sub topic 8
for await...of over Sync Iterables and Promise Arrays
This chapter assumes you know how the sync iteration protocol works, what Symbol.asyncIterator is, and how for await...of consumes an async iterable. Those topics were covered in earlier chapters. Here you will see what happens when you give for await...of something that is not async iterable, such as a plain array or an array of promises. You will also see a common trap in that pattern.
How the loop picks an iterator
When for await...of starts, it first looks for a Symbol.asyncIterator method on the object. If that method is missing, it falls back to Symbol.iterator. It then wraps the sync iterator in an adapter that awaits each value before handing it to the loop body.
So arrays, Sets, Maps, strings, and sync generators all work in for await...of. Every value is awaited. A plain value like 1 comes through unchanged, just one microtask later. A promise is unwrapped to its fulfilled value.
async function main() {
const mixed = [1, Promise.resolve(2), 3];
for await (const value of mixed) {
console.log(value); // 1, 2, 3
}
}
main();Arrays of promises: concurrent start, ordered results
A useful case is an array of promises that are already running. The loop awaits them in array order, but the work itself happens concurrently, because each promise started when you created it.
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function main() {
const tasks = [sleep(300, 'a'), sleep(100, 'b'), sleep(200, 'c')];
console.time('loop');
for await (const value of tasks) {
console.log(value); // a, b, c (array order, not finish order)
}
console.timeEnd('loop'); // about 300 ms, not 600 ms
}
main();The loop body sees 'a' first, even though 'b' finished first. The total time equals the slowest task because all three timers run at the same time. The loop only controls the order in which you observe the results.
| Input to for await...of | When work starts | Order of results |
|---|---|---|
| Array of already-created promises | All at once, before the loop | Array order |
| Async generator | One step at a time, on each `next()` | Yield order |
| Array of plain values | No async work | Array order |
The unhandled rejection trap
Promises in an array get a rejection handler only when the loop reaches them. Suppose a later promise rejects while the loop is still waiting on an earlier one. At that moment nothing is handling the rejection. Node.js reports it as an unhandled rejection, and since Node 15 the default behavior is to crash the process. A try/catch around the loop does not help, because the loop has not reached that promise yet.
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms) =>
new Promise((_, reject) => setTimeout(() => reject(new Error('boom')), ms));
async function main() {
const tasks = [sleep(300, 'slow'), fail(50)];
try {
for await (const value of tasks) {
console.log(value);
}
} catch (err) {
console.error('Caught:', err.message); // may never run in Node.js
}
}
main();A safer version of the same idea:
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms) =>
new Promise((_, reject) => setTimeout(() => reject(new Error('boom')), ms));
async function main() {
const results = await Promise.allSettled([sleep(300, 'slow'), fail(50)]);
for (const r of results) {
console.log(r.status, r.status === 'fulfilled' ? r.value : r.reason.message);
}
// fulfilled slow
// rejected boom
}
main();When this pattern fits
Use for await...of over a promise array when all of these are true:
- The promises cannot reject, or each one already has its own
.catch(). - You want to process results in a fixed order.
- You want to start handling the first result before the last one finishes.
If any of these is false, Promise.all or Promise.allSettled is usually the clearer choice. The next chapter compares sequential and concurrent patterns in more detail.
Exercise
Given const tasks = [sleep(100, 'x'), sleep(400, 'y'), sleep(200, 'z')], roughly how long does a for await...of loop over tasks take, and in what order are the values logged?
Show answer
About 400 ms, the duration of the slowest timer, because all three timers started when the array was created. The values are logged in array order, x, y, z. The z timer finishes at 200 ms, but its value waits until y resolves at 400 ms.
Exercise
Why does wrapping a for await...of loop over an array of promises in try/catch fail to prevent an unhandled rejection in some cases?
Show answer
The loop attaches a handler to each promise only when it reaches that promise. If a later promise rejects while the loop is still awaiting an earlier one, no handler is attached at the moment of rejection. The runtime therefore reports it as unhandled before the try/catch could see it.