【问题标题】:How do I gather an async function * into an array?如何将异步函数 * 收集到数组中?
【发布时间】:2017-12-19 17:08:59
【问题描述】:

假设我有一个像这样的async function * () (setup here):

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 ]

【问题讨论】:

  • Promise.all(f()) 可能是合理的,尽管我认为当前的提案不支持该扩展。
  • 不,我很确定传播语法将保留用于同步迭代。

标签: javascript async-await generator


【解决方案1】:

你能做的最好的就是把它放到一个函数中:

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());

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 1970-01-01
    • 2017-06-07
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    相关资源
    最近更新 更多