Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
282 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...