DEV Community

Cover image for Build pagination with ES6 async generators and iterables
Jeevan Kishore
Jeevan Kishore

Posted on

Build pagination with ES6 async generators and iterables

What the šŸ  is a generator?

Well, according to the definition :

Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.

Fancy, what does this bring to the table? šŸ’­

argh, definition again.. šŸ’¤

Generators in JavaScript -- especially when combined with Promises -- are a very powerful tool for asynchronous programming

A real world scenario?

After all that definition reading, let's jump into the core of it. :octocat:

We had an interesting problem on our hands to tackle. It was to enable pagination to one of our mobile app's on swipe right.

So we use generators for it?

There are other possible solutions, generators are just a cleaner solution.

How to do it?

Create a generator

const asyncGetContent = async function* (){
  const limit = 10; /* content per page */
  let offset = 0; /* index of item to start from */
  let totalCount = -1; /* -1 signifies failure */
  while (offset === 0 || offset < totalCount) {
    try {
      const response = await (await fetch(<<url>>)).json();
      offset = offset + limit;
      totalCount = response["total-count"];
      console.log(`offset + totalCount`, offset, totalCount);
      yield response;
    } catch (e) {
      console.warn(`exception during fetch`, e);
      yield {
        done: true,
        value: "error"
      };
    }
  }

}
Enter fullscreen mode Exit fullscreen mode

That's a lot to understand, let's go through each line.

ā›„ we've limit which defines a variable to set the limit on the results of your choice [need not be a constant]

ā›„ prepare a fetch/ axios/ some API call, shoot it with an await such that we will resolve the resulting promise.

ā›„ yield the response. The return will be a promise to be consumed by the async caller using .next()(we'll get to that in the next section)

ā›„ let's just handle fetch


How do i use this?

All that's left to do is to initiate and call it within an async function as such:

const contentGen = await asyncGetContent(); /* initate the generator */
Enter fullscreen mode Exit fullscreen mode

after initiation, we can call wherever required (ex: right swipe / click of a button) to yield the result

const content = await contentGen.next();
Enter fullscreen mode Exit fullscreen mode

use content [the response from the api in this case] as necessary

If you have questions, let us know in the comments and we are looking forward for your feedback šŸ»

Top comments (0)