如何将异步函数*收集到数组中?

时间:2017-12-19 17:08:59

标签: javascript async-await generator

假设我有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 ]

1 个答案:

答案 0 :(得分:0)

您能做的最好的就是将其放入一个函数中:

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());
相关问题