Async Iterators and Generators in JavaScript

Async Iterators and Generators in JavaScript

In this article, I am going to discuss Async Iterators and Generators in JavaScript with Examples. Please read our previous article where we discussed JavaScript Iterators and Iterables in detail. At the end of this article, you will understand the following pointers.

  1. Async Iterators and Generators in JavaScript
  2. Difference between iterators and Async iterators
  3. Difference between async and regular generators
  4. When to use async generator
  5. Async generator features
  6. Multiple Examples to understand above concepts
Async Iterators and Generators in JavaScript:

Asynchronous iterators as the name imply it allow us to iterator over the data without waiting for other iteration processes i.e.: asynchronously

Async iterators

Asynchronous iterators are same as of other normal iterators except few differences which make it Asynchronous

Below are the few points that make iterable object asynchronous:

  • We need to use Symbol.asyncIterator in place of Symbol.iterator
  • next() method should return a promise.
  • To iterate over an object, we need to use for wait (let item of iterable) loop in place of for (let item of iterable) loop.
Difference between iterators and Async iterators:
IteratorsAsync iterators
Object method that provide iteratorSymbol.iteratorSymbol.asynIterator
next() method value isany value

{value: …, data: true/false}

Promise that resolves to

{value: …, data: true/false}

loop to usefor…offor await…of
Difference between async and regular generators:
GeneratorsAsync generators
Function declarationfunction*asyn function*
next() method value isany value

{value: …, data: true/false}

Promise that resolves to

{value: …, data: true/false}

When to use async generator:

We can use an async generator when we want to access the stream of data and want to log the progress like using the progress bar. For downloading and uploading the big file

Async generator features:
  1. Await can only be used/placed inside an async function.
  2. Functions with the async keyword will always return a promise.
  3. Multiple awaits will always run in sequential order under the same function.
  4. When a promise resolves normally, then await promise returns the result. But in case of rejection it throws the error, just if there were a throw statement at that line.
  5. Async function cannot wait for multiple promises at the same time.
  6. Performance issues can occur if using await after await as many times one statement doesn’t depend on the previous one

Regarding the keyword promise what it is and what does it do will see in Promise chapter let check the simple example of async generators

Example simple async generator:
<html>
<head>
    <title>JavaScript async generator simple example</title>
</head>
<body>
    <script>
        async function asyncGenFunction () {
            const promise = new Promise((resolve, reject) => {
                setTimeout(() => resolve("async generator is calling...!"), 1000)
            });
            const result = await promise;
            // wait till the promise resolves (*)
            console.log(result); // async generator is calling...
        }
        asyncGenFunction();
    </script>
</body>
</html>

Output: Async Iterators and Generators in JavaScript

The above asyncGenFunction() execution stops at await promise line and starts when the promise returns the data with result variable and them it shows the async generator is calling… in one second.

Example-1 async generator with for await…. of:
<html>
<head>
    <title>JavaScript async generator example-1</title>
</head>
<body>
    <script>
        async function* asyncSequence(start, end) {
            for (let i = start; i <= end; i++) {
                yield new Promise((resolve, reject) => {
                    setTimeout(() => {
                        resolve(i);
                    }, 1000);
                });
            }
        }
        (async () => {
            let asySeq = asyncSequence(1, 5);

            for await (let num of asySeq) {
                console.log(num);
            }
        })();
    </script>
</body>
</html>

Output:

Async Iterators and Generators in JavaScript with Examples

An async generator is the same as regular generator with the following different features:

  • The async keyword is placed in front of the function keyword.
  • The yield returns a Promise, instead of a value. The Promise is typically a wrapper of an asynchronous operation.

Notice that in the above example we have setTimeout() to simulate the asynchronous operation.

To iterate over the async generator we need to for await…of loop

Example-2:
<html>
<head>
    <title>JavaScript async generator example-2</title>
</head>
<body>
    <script>
        async function* asyncGenerator() {
            let i = 0;
            while (i < 3) {
                yield i++;
            }
        }

        (async function () {
            for await (let num of asyncGenerator()) {
                console.log(num);
            }
        })();
    </script>
</body>
</html>

Output:

JavaScript Async Iterators and Generators

Example: iterating over async iterables
<html>
<head>
    <title>JavaScript iterating async iterables example</title>
</head>
<body>
    <script>
        const asyncIterable = {
            [Symbol.asyncIterator]() {
                return {
                    i: 0,
                    next() {
                        if (this.i < 3) {
                            return Promise.resolve({ value: this.i++, done: false });
                        }

                        return Promise.resolve({ done: true });
                    }
                };
            }
        };

        (async function () {
            for await (let num of asyncIterable) {
                console.log(num);
            }
        })();
    </script>
</body>
</html>

Output:

JavaScript Async Iterators and Generators Examples

In the next article, I am going to discuss JavaScript function are First-class citizen with Examples. Here, in this article, I try to explain Async iterators and generators in JavaScript with examples. I hope this Async Iterators and Generators in JavaScript article will helps you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *