[英]How do I gather an async function * into an array?
假設我有一個async function * ()
( 在此處設置 ),如下所示:
const f = async function * () {
yield * [ 1, 2, 3 ];
};
我可以收集這樣的結果:
const xs = [];
for await (const x of f()) {
xs.push(x);
}
但是我可以使用...
語法使它更緊湊嗎?
就像是:
const xs = await f(); // xs = [ 1, 2, 3 ]
您可以做的最好的就是將其放入函數中:
const toArray = async f => {
const xs = [];
for await (const x of f) {
xs.push(x);
}
return xs;
};
用法:
// In an async context
const xs = await toArray(f());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.