How to convert async generator to Array in JavaScript?

281 Views Asked by At

I'm looking for a way, using build in function if that's possible, to convert async generator into array in JavaScript.

Example that work with generator:

function* foo() { for (let x = 0; x < 10; ++x) yield x; }

console.log(Array.from(foo()));
console.log([...foo()]);

but the same don't work with async generator.

async function* bar() { for (let x = 0; x < 10; ++x) yield x; }

console.log(Array.from(bar()));
[...bar()];

What is standard, and possible the shortest, way to convert Async generator/iterator into array like with normal generator/iterator?

Can I use standard functions (best if they are ES5 compatible like Array.from).

And to give the context I need this for my Scheme based lisp interpreter called LIPS, I want to be able to call JavaScript function that is async generator and get the results.

this works in beta version of LIPS:

(Array.from (foo))
;; ==> #(0 1 2 3 4 5 6 7 8 9)

but this don't:

(Array.from (bar))
;; ==> #()

The same as in JavaScript.

And I'm not sure if I need to write a function (also not sure how to name it) that will convert async generator into Array, or maybe I need to write loop like do for that. Using iterator protocol I would be able to write code that would not require any new JavaScript.

But I'm not sure if something build in already exists for async generators lik Array.from for normal generators.

I know that you can use while with await for each result of for await of loop, but I'm looking for single function that would just create an array that I can use in LIPS without writing any extra function. Is something like this exists?

0

There are 0 best solutions below