javascriptnode.jsiteratormap-functionasync-iterator

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


Solution

  • 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
        });
    };