Dmi*_*ich 9 javascript iterator node.js map-function async-iterator
假设我们有一个异步生成器:
exports.asyncGen = async function* (items) {
for (const item of items) {
const result = await someAsyncFunc(item)
yield result;
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以映射该生成器?本质上我想这样做:
const { asyncGen } = require('./asyncGen.js')
exports.process = async function (items) {
return asyncGen(items).map(item => {
//... do something
})
}
Run Code Online (Sandbox Code Playgroud)
截至目前.map无法识别异步迭代器。
另一种方法是使用for await ... of ,但这远不如使用.map
提供此方法的迭代器方法提案仍仅处于第 2 阶段。你可以使用一些polyfill,或者编写你自己的辅助函数: map
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
});
};
Run Code Online (Sandbox Code Playgroud)