Sitemap

Member-only story

Async Iterables and Iterators in Javascript

6 min readFeb 8, 2024

--

Async iterables and iterators are the same as synchronous iterables and iterators, except that it wraps the concept of promises instead.

Press enter or click to view image in full size
Async delivery of elements to a unknown consumer

Share it for free using this link. In the previous article titled “Iterables and Iterators in Javascript” there are explanations in detail about this topic. If you haven’t had the chance to read it yet, I highly recommend doing so, as this article will build upon the foundational concepts discussed there.

An Iterator has a next() method that returns an object with two properties, value and done . In the case of an asynchronous iterator, the next() method returns this object as a promise instead.

  • When using the for ... of loop, it accepts an iterable that implements the method using @@iterator available through [Symbol.iterator]().
  • When using the for await ... of loop, it accepts an iterable that implements the method using @@asyncIterator symbol available through [Symbol.asyncIterator](). However, if the method doesn’t exist, it will fall back to using @@iterator.

We can easily create an asynchronous IterableIterator by using async generator method.

async function * createAsyncIterator(...values) {
for(const value of values)
yield value
}

--

--