Given I have an async generator:
async function* generateItems() { // ... }
What's the simplest way to iterate all the results into an array? I've tried the following:
// This does not work const allItems = Array.from(generateItems());
// This works but is verbose const allItems = []; for await (const item of generateItems()) { allItems.push(item); }
(I know this is potentially bad practice in a Production app, but it's handy for prototyping.)
We have to call the async function from another function which can be asynchronous or synchronous (We can pass the array or choose to declare the array in the async function itself) and then return the array from the async function. The basic approach is to include a try-catch block.
An async iterator is like an iterator except that its next() method returns a promise that resolves to the {value, done} object. The following illustrates the Sequence class that implements the iterator interface. (Check it out the iterator tutorial for more information on how to implement Sequence class.)
A generator function (ECMAScript 2015) in JavaScript is a special type of synchronous function which is able to stop and resume its execution at will.
Async/await makes it easier to implement a particular use case of Generators. The return value of the generator is always {value: X, done: Boolean} whereas for async functions, it will always be a promise that will either resolve to the value X or throw an error.
Here is a simple function to convert async iterator to an array without having to include a whole package.
async function toArray(asyncIterator){ const arr=[]; for await(const i of asyncIterator) arr.push(i); return arr; }
Your solution is the only one I know of. Here it is as a TypeScript function:
async function gen2array<T>(gen: AsyncIterable<T>): Promise<T[]> { const out: T[] = [] for await(const x of gen) { out.push(x) } return out }
TypeScript Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With