Search code examples
javascriptasync-await

How can I convert an async iterator to an array?


Given I have an async generator:

async function* generateItems() {
    // ...
}

What's the simplest way to iterate all the results into an array? I've tried the following:

// This does not work
const allItems = Array.from(generateItems());
// This works but is verbose
const allItems = [];
for await (const item of generateItems()) {
    allItems.push(item);
}

(I know this is potentially bad practice in a Production app, but it's handy for prototyping.)


Solution

  • Looks like the async-iterator-to-array npm library does this:

    Install

    npm install --save async-iterator-to-array
    

    Usage

    const toArray = require('async-iterator-to-array')
    
    async function * iterator (values) {
      for (let i = 0; i < values.length; i++) {
        yield values[i]
      }
    }
    
    const arr = await toArray(iterator([0, 1, 2, 3, 4]))
    
    console.info(arr) // 0, 1, 2, 3, 4