List common use cases for generator functions in JavaScript

twitter logo github logo ・1 min read

Hey 👋,

Recently, I finally found a use case for generator functions in JavaScript. But, it was quite particular. I wrote a cli that extracts information from GitHub.

I wanted to split the fetching logic from what I do with it to make it more reusable. Due to rate limit imposed by the GitHub API I had to make multiple calls to get all data I need. Each time, I get a result I want to send it to the caller so It can do something with it. To achieve it I used a pattern called Inversion of control. Generator functions fits well with this pattern. You can see my usage of it here.

I was wondering if it exists more common use cases for generator functions ?

twitter logo DISCUSS (3)
markdown guide
 

My favorite application of generator functions probably has to be async iterators within the context of pagination for data fetching. My react applications can defer asking for more pages until they've scrolled past a certain point on the current view.

 

Didn't thought about it 👍, do you have an example of implementation ?

 
async function* paginate(current) {
  const url = new URL('/api/data', location.href);
  while (1) {
    url.searchParams.set('from', current);
    const res = await fetch(url.href);
    if (res.ok) {
      let j = await res.json();
      let page = yield j.data;
      current = page == null ? j.next : page === -1 ? j.prev : j.next;
    } else {
      throw await (res.headers.get('content-type') === 'application/json' ? res.json() : res.text());
    }
  }
}

Although I'd recommend something almost totally different with skips and all, it's up to you.

Classic DEV Post from Apr 12

Introducing The Recursive `Pipe` and `Compose` Types

It turns out, the recursive Pipe (and Compose) types offer key advantages over ...

🦁 Yvonnick FRIN profile image
Open source advocate at @ZenikaIT. I'm a @NantesJS meetup co-organizer on my spare time.