Asynchronous iteration and async generators
Quick answer
An asynchronous iterable delivers iteration results through promises. for await...of waits for each step and is useful for data arriving over time.
How it works
An async iterable defines Symbol.asyncIterator; the returned iterator’s next returns a promise for an iterator result. Promise is a future-result object; await pauses an async function until settlement (the next chapter develops this concept further). async function* creates an async generator and can await inside its body. for await...of can also adapt synchronous iterables. Its early-exit path awaits return when present. Wrap browser or script examples in an async function rather than assuming top-level await is supported.
async function* g(){yield 2;yield 5;} (async()=>{const out=[];for await(const n of g())out.push(n);console.log(JSON.stringify(out));})();Expected output in Node.js:
[2,5]The loop awaits each result and preserves order.
async function* g(){try{yield 1;yield 2;}finally{console.log("closed");}} (async()=>{for await(const n of g()){console.log(n);break;}console.log("after");})();Expected output in Node.js:
1closedafterEarly exit awaits generator cleanup.
Common mistakes
An async iterator next result is a promise, not the result object itself. Do not confuse sequential iteration with parallel processing or assume async iterator helpers exist because synchronous helpers do.
Practice
Trace each await and early break in a finite async generator with a finally block.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Asynchronous iteration and async generators — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Which hook selects asynchronous iteration?
What does async generator next() return?
Does for await...of automatically process all items in parallel?
What is the exact console output in Asynchronous iteration and async generators example 1?
async function* g(){yield 2;yield 5;} (async()=>{const out=[];for await(const n of g())out.push(n);console.log(JSON.stringify(out));})();What is the exact console output in Asynchronous iteration and async generators example 2?
async function* g(){try{yield 1;yield 2;}finally{console.log("closed");}} (async()=>{for await(const n of g()){console.log(n);break;}console.log("after");})();