How can I convert an async iterator to an array?

房东的猫 提交于 2020-06-23 01:47:05

问题


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.)


回答1:


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


来源:https://stackoverflow.com/questions/58668361/how-can-i-convert-an-async-iterator-to-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!