DEV Community


Discussion on: JavaScript Generators

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()) {

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.

ajmeyghani profile image
AJ Meyghani Author

Thanks for your comment Kushan!