Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an async iterator to an array?

Tags:

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.)

like image 929
Sam Avatar asked Nov 02 '19 04:11

Sam


People also ask

Can async return an array?

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.

What is async iterator?

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.)

Are generator functions asynchronous?

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.

Does async await use generators?

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.


2 Answers

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; } 
like image 134
rettigcd Avatar answered Oct 21 '22 11:10

rettigcd


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

like image 42
mpen Avatar answered Oct 21 '22 12:10

mpen