DEV Community

Iterators in JavaScript

Akshendra Pratap Singh on July 29, 2018

Many a times you wake up and realize that today you will be traversing through an array or maybe many arrays. But you don't worry about it, you hav...
Collapse
 
victor profile image
Victor.

What will be a real implementation for iterators?

Collapse
 
kepta profile image
Kushan Joshi • Edited

If you are talking about a real application for iterators, I find it incredibly useful to do paged requests.
These requests are requests which only give a certain chunk of data corresponding to the page. Some API's also do not provide a way to see how many pages are there in total.

Example

async function* fetchTweet() {
  let page = 0;
  let response;
  while (true) {
    response = await fetch('https://twitter.com/latest?page=' + page++);
    if (response.length === 0) {
      break;
    }
    yield response;
  }
}

async function getAllTweets() {
  for (const result of await getAllTweets()) {
    // do something one by one with result
  }

  // handle all of them together
  const allTweets = await Promise.all([...getAllTweets()]);
}

I wrote a similar article on Iterators, feel free to check it out dev.to/kepta/how-i-learned-to-stop...