Syntax
async function* name() {
yield await value;
}
for await (const val of asyncIterable) { }Examples
Basic Async Generator
Yielding values that resolve asynchronously, one at a time.
async function* fetchPages(baseUrl, totalPages) {
for (let page = 1; page <= totalPages; page++) {
const response = await fetch(`${baseUrl}?page=${page}`);
const data = await response.json();
yield data;
}
}
async function processAllPages() {
for await (const pageData of fetchPages("/api/items", 3)) {
console.log("Received page:", pageData);
}
}Simulating a Delayed Stream
A simplified example showing values arriving over time.
async function* countWithDelay(max) {
for (let i = 1; i <= max; i++) {
await new Promise(resolve => setTimeout(resolve, 500));
yield i;
}
}
async function run() {
for await (const num of countWithDelay(3)) {
console.log(num); // 1, 2, 3 - each one arriving 500ms apart
}
}
run();Best practices
- Use async generators for processing data that naturally arrives in chunks over time, like paginated APIs or streaming responses
- Use for await...of instead of manually calling .next() and awaiting each result - it handles the iteration protocol for you
- Remember an async generator function always returns an async iterable, regardless of what individual yields resolve to
- Combine with try/catch inside the for await...of loop to handle errors from individual chunks without stopping the entire stream
At a glance
- Purpose
- Application logic and interaction
- File extension
- .js ยท .mjs
- Runs in
- Browsers and JavaScript runtimes
- Usually used with
- HTML, CSS and Web APIs
Specifications & further reading
Related JavaScript documentation
Async/Await
Async/await is modern JavaScript syntax for handling asynchronous operations, making asynchronous code look and behave like synchronous code. The async keyword marks a function as asynchronous, and await pauses execution until a Promise resolves. This approach makes asynchronous code more readable and easier to understand than traditional Promise chains or callbacks.Promises
A Promise represents a value that may not be available yet - the eventual result of an asynchronous operation. It exists in one of three states: pending, fulfilled, or rejected. then() handles a successful result, catch() handles an error, and finally() runs regardless of outcome. Promises are the foundation that async/await is built on top of.Promise.all(), allSettled(), race(), any()
These static methods handle multiple promises at once. Promise.all() waits for every promise to resolve, but rejects immediately if any one fails. allSettled() waits for all to finish regardless of outcome, giving you both successes and failures. race() resolves or rejects as soon as the first promise settles. any() resolves as soon as the first one succeeds, ignoring rejections unless all fail.Fetch API
The Fetch API provides a modern, promise-based way to make HTTP requests, replacing the older XMLHttpRequest. fetch() returns a promise that resolves to a Response object once headers are received - note that a Response is only considered "ok" if the status is 2xx, so checking response.ok is essential, since fetch() does not reject on HTTP error statuses.
Async/await is modern JavaScript syntax for handling asynchronous operations, making asynchronous code look and behave like synchronous code. The async keyword marks a function as asynchronous, and await pauses execution until a Promise resolves. This approach makes asynchronous code more readable and easier to understand than traditional Promise chains or callbacks.Promises
A Promise represents a value that may not be available yet - the eventual result of an asynchronous operation. It exists in one of three states: pending, fulfilled, or rejected. then() handles a successful result, catch() handles an error, and finally() runs regardless of outcome. Promises are the foundation that async/await is built on top of.Promise.all(), allSettled(), race(), any()
These static methods handle multiple promises at once. Promise.all() waits for every promise to resolve, but rejects immediately if any one fails. allSettled() waits for all to finish regardless of outcome, giving you both successes and failures. race() resolves or rejects as soon as the first promise settles. any() resolves as soon as the first one succeeds, ignoring rejections unless all fail.Fetch API
The Fetch API provides a modern, promise-based way to make HTTP requests, replacing the older XMLHttpRequest. fetch() returns a promise that resolves to a Response object once headers are received - note that a Response is only considered "ok" if the status is 2xx, so checking response.ok is essential, since fetch() does not reject on HTTP error statuses.