Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Statements and Declarations

The for await...of statement

Reference for JavaScript for await...of: looping over async iterables and async generators, awaiting promises in arrays, error handling and top-level use.

The for await...of statement loops over an async iterable: an object with a Symbol.asyncIterator method, such as the result of an async generator. On every iteration it waits for the next value before running the body. It can only be used where await is allowed: inside an async function, or at the top level of a module.

It also accepts ordinary synchronous iterables. Then each value is awaited, so an array of promises is handled in order.

JavaScript
for await (const chunk of source) {
  console.log(chunk);
}

Try it

JS An async generator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Promises in an array and error handling

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
for await (variable of iterable) {
  statement
}
Part Description
variable A binding (const, let, var) or destructuring pattern, or an assignment target, that receives each awaited value.
iterable An async iterable, or a sync iterable whose values may be promises.

Exceptions: a TypeError if the value is neither async-iterable nor iterable. A rejected promise or an error thrown by the source is thrown at the loop, so wrap it in try...catch.

Usage notes

  • Sequential. The next value is requested only after the body finishes. To run work in parallel, start the promises first and use Promise.all().
  • Where it works. In async functions, async generators and top-level module code. Elsewhere it is a SyntaxError.
  • Sync iterables. Each value is passed through await, but all promises in an array already started running when created. Awaiting them in order does not delay them, only the loop.
  • Closing. break, return or a throw calls the async iterator's return() method (and waits for it), so cleanup in finally blocks of an async generator runs.
  • Typical sources. Async generators you write, Node.js readable streams, and in modern browsers ReadableStream objects from fetch() (check the compatibility table for stream async iteration).
  • Rejections. If a promise in a sync iterable rejects before the loop reaches it, make sure the loop (or other handlers) will handle it, or you may see unhandled-rejection warnings.
  • Do not mix up with await in a plain loop. for (const p of promises) { await p } is similar for arrays but does not support async iterables.

Browser support

Supported in current browsers and Node.js; it is part of the language since ES2018. Async iteration of browser streams is more recent, so check a compatibility table for that.