DEV Community

Discussion on: JavaScript Generators

Collapse
 
kepta profile image
Kushan Joshi

Great article AJ, you can also use for-await-of but it works for async iterables, you can also use them with an array of promises.

Here's how you would create an async iterable.

const fetchNextPage = page => Promise.resolve(page);

async function* asyncGen() {
  let page = 0;
  while (page < 10) yield fetchNextPage(page++);
}

for await (const g of asyncGen()) {
  console.log(g);
}

The best part about this approach is concurrency, the async generator asyncGen only creates a new promise when asked for, and the for-await-of automatically awaits at the start of for loop, resolves it and puts it as the const g.

Collapse
 
ajmeyghani profile image
AJ Meyghani

Thanks for your comment Kushan!