[英]How do I gather an async function * into an array?
Suppose I have an async function * ()
( setup here ) like this: 假设我有一个
async function * ()
( 在此处设置 ),如下所示:
const f = async function * () {
yield * [ 1, 2, 3 ];
};
I can gather the results like this: 我可以收集这样的结果:
const xs = [];
for await (const x of f()) {
xs.push(x);
}
But can I use the ...
syntax to make this more compact? 但是我可以使用
...
语法使它更紧凑吗?
Something like: 就像是:
const xs = await f(); // xs = [ 1, 2, 3 ]
The best you can do is put it into a function: 您可以做的最好的就是将其放入函数中:
const toArray = async f => {
const xs = [];
for await (const x of f) {
xs.push(x);
}
return xs;
};
Usage: 用法:
// In an async context
const xs = await toArray(f());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.