Sub topic 8
for await...of over Sync Iterables and Promise Arrays
The earlier chapters used for await...of on async iterables, meaning objects with a Symbol.asyncIterator method. The loop also accepts ordinary sync iterables: arrays, strings, Maps, Sets, and sync generators. That fallback is convenient, but it causes several subtle bugs, especially when the array holds promises.
This chapter assumes you already know the sync iteration protocol (Symbol.iterator, next(), { value, done }), the async iteration protocol, and basic for await...of usage from earlier chapters. You should also be comfortable with promises and the microtask queue.
How the loop picks an iterator
When for await...of starts, it looks for an iterator in a fixed order:
- If the object has a
Symbol.asyncIteratormethod, the loop calls it and uses the async iterator it returns. - If not, the loop looks for
Symbol.iterator. If it finds one, it calls it and wraps the resulting sync iterator in an internal adapter. The specification calls this adapter an async-from-sync iterator. - If neither method exists, the loop throws a
TypeErrorsaying the value is not async iterable.
The adapter makes a sync iterator behave like an async one. Each time the loop calls next() on the adapter, the adapter:
- calls
next()on the sync iterator and gets{ value, done }, - passes
valuethroughPromise.resolve(), so plain values, promises, and thenables are all treated the same way, - returns a promise that fulfills with
{ value: resolvedValue, done }once that value settles.
The adapter awaits the value only. It does not await done, and it does not await the iterator itself. A sync iterable that returns a promise of an array is not iterated as that array. The rule is narrow: if the item is a promise, the loop body gets what the promise resolves to.
Plain values still go through the microtask queue
Every value gets awaited, so even a plain array of numbers produces at least one microtask hop per item. This is the first behavior difference from for...of:
async function main() {
const loop = (async () => {
for await (const x of ['a', 'b']) {
console.log(x);
}
})();
console.log('after loop started');
await loop;
}
main();
// after loop started
// a
// bWith a plain for...of, a and b would print before after loop started, because the whole loop would run synchronously. With for await...of, the async function pauses at the first next() call and hands control back to the caller.
This matters in two situations:
- Ordering assumptions. Code that expects the loop to finish before the next statement in the caller runs will break.
- Overhead. Each item costs several promise allocations and microtask turns. For a large array of plain values,
for await...ofis measurably slower thanfor...ofand gains you nothing. Usefor await...ofonly when items might be promises or the source might be async.
Iterating an array of promises
This is the most common reason to use the fallback. You have an array of promises and want to handle each result in order:
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function main() {
const start = Date.now();
const promises = [sleep(300, 'A'), sleep(200, 'B'), sleep(100, 'C')];
for await (const value of promises) {
console.log(value, Date.now() - start);
}
}
main();
// A ~300
// B ~300
// C ~300All three timers started when map-style creation built the array, before the loop began. The loop then waits for them in array order. C finished first, at about 100 ms, but the loop could not deliver it until A was done. After A arrives at about 300 ms, B and C are already settled, so they come out almost at once.
Two consequences follow:
- The work runs concurrently, because the promises existed before the loop started.
for await...ofdid not cause that concurrency. Building the array did. - Results come out in source order, not completion order. A slow early item holds back every item behind it.
Eager arrays versus lazy sync generators
The same promises behave very differently when a sync generator creates them only on request:
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
function* lazyTasks() {
for (const ms of [300, 200, 100]) {
yield sleep(ms, ms); // timer starts only when next() is called
}
}
async function main() {
const start = Date.now();
for await (const value of lazyTasks()) {
console.log(value, Date.now() - start);
}
}
main();
// 300 ~300
// 200 ~500
// 100 ~600The adapter calls next() on the generator, gets one promise, and awaits it. Only then does it call next() again, which starts the next timer. The tasks run one after another.
| Source | When promises are created | Execution | Total time (300/200/100 ms) |
|---|---|---|---|
| `[p1, p2, p3]` array | Before the loop | Concurrent | about 300 ms |
| Sync generator yielding promises | One per `next()` call | Sequential | about 600 ms |
| Async generator awaiting inside | One per `next()` call | Sequential | about 600 ms |
The loop syntax is the same in all three rows. Timing depends on when the promises are created, not on the loop. The next chapter, "Sequential Loops versus Concurrent Work," covers how to choose between these deliberately.
The unhandled rejection trap
Iterating an eager array of promises has a dangerous failure mode. Suppose a later promise rejects while the loop is still waiting on an earlier one:
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function main() {
const promises = [
sleep(200, 'slow'),
Promise.reject(new Error('fast fail'))
];
try {
for await (const value of promises) {
console.log(value);
}
} catch (err) {
console.error('Caught:', err.message);
}
}
main();You might expect slow, then Caught: fast fail. In Node.js 15 and later, the process usually crashes instead, with an unhandled rejection error and exit code 1. The reason:
- The second promise rejects immediately.
- The loop is awaiting the first promise, so nothing has attached a handler to the second one.
- When the microtask queue drains with a rejected promise that has no handler, Node's default
--unhandled-rejections=throwmode treats it as an uncaught exception. - The
try/catchwould only have caught the error 200 ms later, when the loop reached that item.
Browsers log Uncaught (in promise) and keep running, and the catch block runs later. Node terminates the process.
Fixes
Choose the fix based on what you want to happen when a promise fails.
Fail fast, all-or-nothing. Use Promise.all. It attaches handlers to every promise immediately:
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function main() {
try {
const values = await Promise.all([
sleep(200, 'slow'),
Promise.reject(new Error('fast fail'))
]);
console.log(values);
} catch (err) {
console.error('Caught:', err.message); // Caught: fast fail
}
}
main();Process every outcome in order. Turn each promise into one that never rejects before you loop:
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const settle = (p) =>
p.then(
(value) => ({ ok: true, value }),
(error) => ({ ok: false, error })
);
async function main() {
const promises = [
sleep(200, 'slow'),
Promise.reject(new Error('fast fail'))
].map(settle);
for await (const result of promises) {
if (result.ok) console.log('value:', result.value);
else console.error('error:', result.error.message);
}
}
main();
// value: slow
// error: fast failKeep the original promises but stop the crash. Attach a no-op handler to each one. The loop still awaits the original promise, so it still sees the rejection:
promises.forEach((p) => p.catch(() => {}));This is the smallest change, but it is easy to forget and hides intent. settle or Promise.allSettled is usually clearer.
Early exit and cleanup with sync sources
The adapter forwards return() to the sync iterator. If you break, return, or throw inside the loop body, a sync generator's finally block runs:
function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('sync cleanup');
}
}
async function main() {
for await (const value of source()) {
console.log(value);
if (value === 1) break;
}
}
main();
// 1
// sync cleanupArray, string, Map, and Set iterators have no return() method, so leaving the loop early skips nothing for them. It also does not cancel promises in an array. Timers, fetches, and database calls that are already running keep running after the loop exits.
One edge case involves a sync generator that yields a promise that rejects. In engines that follow the 2023 spec revision, the adapter closes the sync iterator, so the generator's finally runs before the error reaches your catch. Older engines did not do this and could leave the generator suspended. If cleanup really matters, put the awaiting inside an async function*, where try/finally behavior is the same in every engine.
Other sync iterables
Any sync iterable works, and each item is awaited:
async function main() {
for await (const ch of 'hi') console.log(ch); // h, i
const m = new Map([['a', Promise.resolve(1)]]);
for await (const entry of m) console.log(entry); // [ 'a', Promise { 1 } ]
}
main();The Map result catches people out. The adapter awaits each item, and here each item is the entry array ['a', promise]. Arrays are not thenables, so the entry comes through unchanged, and the promise inside it is never awaited. Only top-level items are unwrapped.
Summary of rules
| Behavior | for...of | for await...of over a sync iterable |
|---|---|---|
| Needs an async context | No | Yes |
| Promise items | Delivered as promises | Delivered as resolved values |
| Nested promises inside items | Untouched | Untouched |
| Microtask hop per item | No | Yes |
| `break` calls `return()` | Yes | Yes, forwarded to the sync iterator |
| Concurrency | None | Comes only from promises created before the loop |
Exercise
An array is built with const ps = urls.map((u) => fetch(u)); and consumed with for await (const res of ps) { ... }. Do the requests run sequentially or concurrently, and in what order does the loop body see the responses?
Show answer
They run concurrently, because map starts every fetch before the loop begins. The loop body still sees the responses in array order. A slow first response holds back every later one, even if those finished earlier.
Exercise
Rewrite function* tasks() { yield sleep(300, 'a'); yield sleep(100, 'b'); } so that both timers start immediately while for await...of still consumes the results in order. Why does your version run faster?
Show answer
Create the promises up front, for example const ps = [sleep(300, 'a'), sleep(100, 'b')]; for await (const v of ps) { ... }. It finishes in about 300 ms instead of about 400 ms because both timers run at the same time. The generator version starts each timer only when the adapter calls next().
Exercise
A Node.js script loops with for await over [slowPromise, rejectsQuicklyPromise] inside try/catch, and the process exits with an unhandled rejection error. Explain why, and give two fixes.
Show answer
The loop attaches a handler only to the promise it is currently awaiting. The second promise rejects while the loop waits on the first, so it has no handler, and Node's default unhandled-rejection mode crashes the process before the loop reaches it. Fixes: use await Promise.all(...) (or Promise.allSettled) so every promise gets a handler immediately, or map each promise through p.then(v => ({ ok: true, v }), e => ({ ok: false, e })) before looping.