DEV Community

Discussion on: List common use cases for generator functions in JavaScript

Collapse
 
yvonnickfrin profile image
🦁 Yvonnick FRIN

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

Collapse
 
zanehannanau profile image
ZaneHannanAU
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.