Asynchronous iterators allow iterating over data, which comes asynchronously. For example, downloading something chunk-by-chunk over the network.
With asynchronous generators, it becomes more convenient. To be more precise, let’s start at grasping the syntax.
Async Iterators
Async iterators are, generally, like regular iterators. But, there are several syntactical differences.
A regular iterable object is the following:
For making the object asynchronously iterable, it is necessary to act in this way:
- Using Symbol.asyncIterator rather than Symbol.iterator.
- A promise should be returned by the next().
- It is necessary to use the for await (let item of iterable) loop for iterating over an object like that.
Let’s check out an example:
Async Generators
JavaScript also supports generators. They are also considered iterable.
Let’s consider a regular generator that creates an order of values from the start to the end, like this:
So, await can be used in regular generators. There is no space for a delay in the for..of loop, as all the values should come asynchronously.
For using await in the generator body, you can prepend it with async in this way:
There appeared an async generator, which is iterable with for await...of
Another difference of the asynchronous generator is that the generator.next() method is asynchronous, too and returns promises.
So, in a regular generator,result = generator.next() is applied for getting values. In the async generator, await is added in this way:
results = await generator.next(); // results = {value: ..., done: true/false}
Async Iterables
To transform an object into an iterable, Symbol.iterator should be added to it, like this:
let range = {
from: 1,
to: 3,
[Symbol.iterator]() {
return <object with next to make the range iterable>
}
}
A frequently used practice for the Symbol.iterator is returning a generator, instead of a plain object using next.
Let’s see an example:
The custom object range is considered iterable. The *[Symbol.iterator] generator performs the logic for the listing values. Here is an example:
The values now will come with a delay of a second between them.
Summary
Regular generators and iterators work perfectly with the data that takes no time for generating.
While waiting for the data to come asynchronously with delays. Here for await..of is used rather than for..of.
Also, async generators can be used for processing streams of data that flow chunk-by-chunk.
Practice Your Knowledge
Quiz Time: Test Your Skills!
Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.