AceDevHub
Advanced JavaScript Interview QuestionsAdvancedConcept

JavaScript · Question 91

How do async generators support incremental asynchronous data production, and how should cleanup be handled?

Direct answer

An async generator combines async function suspension with generator yielding, producing an async iterator whose next() calls return Promises; consumers can process values incrementally, and producer cleanup should live in try/finally so iterator termination releases resources.

An async generator declared with async function* can await asynchronous work and then yield values one at a time. Calling next() returns a Promise for an iterator result, which is why for await...of is the natural consumer syntax.

This structure is useful for paginated APIs, event or message sources, database-like cursors exposed to JavaScript, and transformations where producing the entire result array first would waste memory or delay first output. The consumer asks for successive results rather than receiving one giant Promise for all data.

  • Place resource release in finally around the producer loop.
  • When a consumer exits a for await...of loop early, iterator closing gives the iterator a chance to terminate rather than silently leaving the producer active.
  • For real streams, also understand the stream API’s own cancellation and backpressure semantics; async iteration is an interface, not a universal replacement for stream-specific controls.