如何将异步迭代器转换为数组? [英] 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);
}
(我知道这在Production应用程序中可能是不好的做法,但对于原型制作很方便.)
(I know this is potentially bad practice in a Production app, but it's handy for prototyping.)
推荐答案
Looks like the async-iterator-to-array
npm library does this:
安装
npm install --save async-iterator-to-array
用法
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
这篇关于如何将异步迭代器转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文