1

Suppose I have an async function * () (setup here) like this:

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 ]
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
  • 1
    `Promise.all(f())` might be reasonable, though I don't think the current proposal supports that extension. – Bergi Dec 19 '17 at 19:37
  • No, I'm pretty sure spread syntax will stay reserved for synchronous iterables. – Bergi Dec 19 '17 at 19:38
  • Not a complete remedy but there is a proposal for a closely related feature: https://github.com/tc39/proposal-array-from-async – ProgrammerPer Jan 20 '23 at 18:06

1 Answers1

1

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());
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245