Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map over async generators?

Let's say we have an async generator:

exports.asyncGen = async function* (items) {
  for (const item of items) {
    const result = await someAsyncFunc(item)
    yield result;
  }
}

is it possible to map over this generator? Essentially I want to do this:

const { asyncGen } = require('./asyncGen.js')

exports.process = async function (items) {
  return asyncGen(items).map(item => {
    //... do something
  })
}

As of now .map fails to recognize async iterator.

The alternative is to use for await ... of but that's nowhere near elegant as with .map

like image 443
Dmitry Kankalovich Avatar asked Apr 25 '26 05:04

Dmitry Kankalovich


1 Answers

The iterator methods proposal that would provide this method is still at stage 2 only. You can use some polyfill, or write your own map helper function though:

async function* map(asyncIterable, callback) {
    let i = 0;
    for await (const val of asyncIterable)
        yield callback(val, i++);
}

exports.process = function(items) {
    return map(asyncGen(items), item => {
       //... do something
    });
};
like image 74
Bergi Avatar answered Apr 26 '26 19:04

Bergi