🟑 MediumModern JSπŸ“– Theory Question

What are Async Generators and Async Iterators?

πŸ’‘

Hint

function* + async = yield Promises lazily; consumed with for await...of

Full Answer

Async generators combine generator syntax with async/await β€” they yield values asynchronously and are consumed with for await...of.

// Async generator β€” paginated API fetcher
async function* fetchPages(url) {
  let page = 1;
  while (true) {
    const res = await fetch(`${url}?page=${page++}`);
    const { items, hasMore } = await res.json();
    yield items; // pause, give back items, resume on next iteration
    if (!hasMore) return; // done
  }
}

// Consume with for await...of
async function loadAll() {
  const allItems = [];
  for await (const items of fetchPages('/api/data')) {
    allItems.push(...items);
    if (allItems.length >= 100) break; // can stop early!
  }
  return allItems;
}

// Streaming data (Fetch Streams API)
async function* streamLines(url) {
  const reader = (await fetch(url)).body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';
  while (true) {
    const { done, value } = await reader.read();
    if (done) { if (buffer) yield buffer; return; }
    buffer += decoder.decode(value);
    const lines = buffer.split('\n');
    buffer = lines.pop();
    for (const line of lines) yield line;
  }
}
πŸ’‘ Async generators are perfect for paginated APIs, event streams, or any sequence of values that arrive asynchronously over time.

More Modern JS Questions

🟑 MediumWhat are generators and when would you use them?β†’πŸŸ’ EasyWhat is optional chaining (?.) and nullish coalescing (??)?β†’πŸŸ’ EasyWhat are tagged template literals and what are they used for?β†’πŸŸ’ EasyExplain destructuring for objects and arrays β€” including defaults, renaming, rest, and nesting.β†’

Practice this in a timed sprint β†’

5 free questions, no signup required

⚑ Start Sprint