Iterators and Generators again... (asynchronous ones)
Tags: javascript, node, webdev, tutorial
Published: 2024-03-17 17:23:45

Last time around here, we learned about Iterators and Generators in JavaScript. We also gazed on why it is needed, how to utilize this functionality, and a tutorial example of implementing the iterators and generators.

If you are not familiar with this concepts then I would request you all to check out my previous article on **[Iterators and Generators](https://dev.to/naineel12/iterators-and-generators-in-javascript-1ip9)**.

Now that you are familiar with iterators and generators, let's look at asynchronous ones (I swear this won't be a huge one :D).

##Async Iterators

In JavaScript, async iterators are an extended functionality of the normal iterators. To make an object an async iterable, it must implement the async iterable protocol, which is indicated by the presence of the `Symbol.asyncIterator` method. This method should return a `next` method which should return a Promise which will essentially fetch the data from the desired endpoint by performing asynchronous operation.

Let's take a look at coded example of the same to grasp the concept in better manner -

```javascript
const someKindOfAsyncOperation = async (id) => {
    return new Promise((res, rej) => {
        setTimeout(() => {
            res(`Returning data of User: ${id}`)
        })
    })
}

const obj = {
    [Symbol.asyncIterator] : async function* (){
        for(let i = 0; i < 5; i++){
            const value = await someKindOfAsyncOperation(i);
            yield value;
        }
    }
};

(async () => {
  for await (const value of obj) {
    console.log(value); //Returning data of User: 0 ...
  }
})();
```

Here, `someKindOfAsyncOperation` is an asynchronous operation which loosely relates to the API calls for fetching the user details. We have used generators way of implementing the iterators because of its usability. 

During the asynchronous operation, the function will be halted at the `yield` keyword until the `for...of` loop calls for the `next` method of the object `obj`. The code structure remain very similar, the major changes are the introduction of the asynchronous operations.

##Async Generators

Async Generators are very useful for implementing Async Iterators. It removes the boilerplate code that we had to write every time implementing Iterators or Async Iterators.

Well for the spoilers, we have already made use of the Async Generator earlier in this article. So let's just dive right into it -

```javascript
const someKindOfAsyncOperation = async (id) => {
    return new Promise((res, rej) => {
        setTimeout(() => {
            res(`Returning data of User: ${id}`)
        })
    })
};


async function* asyncGenerator() {
  for (let i = 0; i < 5; i++) {
    const value = await someKindOfAsyncOperation(i);
    yield value;
  }
};

(async () => {
  for await (const value of asyncGenerator()) {
    console.log(value); //Returning data of User: 0 ...
  }
})();
```

Here in the code, the IIFE will be called, which will call the `next` method obtained from the `asyncGenerator()` and it will call the asynchronous function `someKindOfAsyncOperation` which upon resolving gives the desired output. and then `for await...of` loop will call the `next` function again which will yield the next value from the `asyncGenerator` generator function and so on and so forth, all of the desired output will be obtained in the way we want.

For simplicity sake we have used a mock asynchronous operation, we can easily extend this kind of functionality to fetch sequential or custom data.

So... **THANK YOU!!**🎉🫡

I would like to thank you for reading till here and appreciate your patience. It would mean the world to me if you give feedbacks/suggestions/recommendations below.

PS:

>I typically write these articles in the TIL form, sharing the things I learn during my daily work or afterward. I aim to post once or twice a week with all the things I have learned in the past week.