Intermediate LevelJavaScript & TypeScript
How do async generators and for await...of loops work in JavaScript?
❓ Interview Prompt: Explain async generator syntax (async function*), yielding Promises, and consuming async iterables.
Async Generators combine generator functions (function*) with async/await, yielding Promises sequentially over time.
Key Syntax:
•
Declaration:
async function* generateStream().•
Yielding:
yield await fetchChunk().•
Consumption: Consumed using the
for await (const chunk of stream) loop.Use Cases:
Streaming paginated API responses, processing large data files in chunks, WebSocket message feeds.
Code Implementation Example
javascript
// Async generator fetching paginated API pages
async function* fetchPaginatedUsers(maxPages = 3) {
for (let page = 1; page <= maxPages; page++) {
const res = await fetch(`/api/users?page=${page}`);
const data = await res.json();
yield data.users; // Yields array of users per page asynchronously
}
}
// Consuming async iterable with for await...of loop
async function processAllUsers() {
for await (const userBatch of fetchPaginatedUsers()) {
console.log('Received page chunk:', userBatch.length);
}
}💡Streaming paginated API batches with async generator function and for await...of loop.
🎯 Interview Key Takeaway
Use async generators and for await...of to stream asynchronous data chunks sequentially without loading everything into memory.
#Async Generators#Streaming#Iterators#Intermediate
Back to all JavaScript & TypeScript Questions→