Basic For-Await-Of Syntax
You'll learn: How to write for-await-of loops to iterate over async iterables and handle promises automatically.
The Core Syntax
A for-await-of loop looks almost identical to a regular for-of loop, but with the await keyword added:
for await (const item of asyncIterable) {
// Use item here — it's already unwrapped from its promise
}
Think of it like this: a regular for-of loop hands you items directly, while for-await-of waits for each promise to resolve before handing you the unwrapped value.
How It Differs from For-Of
With a regular for-of loop over promises, you'd get promise objects and need to manually await each one:
// Regular for-of with promises (awkward)
for (const promise of arrayOfPromises) {
const value = await promise; // Manual await
console.log(value);
}
With for-await-of, the awaiting happens automatically:
// For-await-of (clean)
for await (const value of arrayOfPromises) {
console.log(value); // Already resolved!
}
Async Context Required
Just like await, you can only use for-await-of inside an async function:
async function processStream(asyncIterable) {
for await (const chunk of asyncIterable) {
console.log('Received:', chunk);
}
}
The loop waits for each promise to settle before continuing to the next iteration, maintaining sequential order.
Key Takeaway: for-await-of adds await between for and of, automatically unwrapping promises from async iterables or arrays of promises, and must be used inside an async function context.