DEV Community

Discussion on: Iterators in JavaScript

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...