Async Iterators

Learn how to use a generator in place of a standard iterator.

The iterators we’ve seen so far return a value synchronously from their next() method. However, in JavaScript and especially in Node.js, it’s very common to have iterations over items that require an asynchronous operation to be produced.

Imagine, for example, to iterate over the requests received by an HTTP server, over the results of an SQL query, or over the elements of a paginated REST API. In all those situations, it’d be handy to be able to return a promise from the next() method of an iterator, or even better, use the async/await construct.

Well, that’s exactly what async iterators are; they’re iterators returning a promise, and since that’s the only extra requirement, it means that we can also use an async function to define the next() method of the iterator. Similarly, async iterables are objects that implement an @@asyncIterator method, or in other words, a method accessible through the Symbol.asyncIterator key, which returns an async iterator synchronously.

Async iterables can be looped over using the for await...of syntax, which can only be used inside an async function. With the for await...of syntax, we’re essentially implementing a sequential asynchronous execution flow on top of the Iterator pattern. Essentially, it’s just syntactic sugarSyntactic sugar is usually a shorthand for a common operation that could also be expressed in an alternate, more verbose, form. for the following loop:

Get hands-on with 1200+ tech skills courses.