Daniel A. White
Daniel A. White

Reputation: 191048

Simplify async-await with array iteration in Typescript

Is there a simpler way to express this syntax in Typescript, without Promise.all and Array.prototype.map?

const items = [...];
await Promise.all(items.map(async item => {
    doSomething(item);
    const result = await doSomethingAsync(item);
    doSomethingMore(result, item);
});

Upvotes: 3

Views: 1413

Answers (1)

Estus Flask
Estus Flask

Reputation: 223104

ES5 array methods don't fully support async and generator functions, that's one of the reasons why for and other loop statements should be preferred to forEach in ES6.

In this case map is partially misused, because it doesn't manage array values. If promises should be resolved in parallel, it likely should be:

items = await Promise.all(items.map(async item => {
    doSomething(item);
    const result = await doSomethingAsync(item);
    doSomethingMore(result, item);
    return item;
});

Not much simpler but possibly semantically correct. If do.. functions modify item to the point its type changes, const newItems = await Promise.all(...) also makes it easier to manage item types.

If they should be resolved in series and no Promise.all has to be involved, this can be for..of:

for (const item of items) {
    doSomething(item);
    const result = await doSomethingAsync(item);
    doSomethingMore(result, item);
});

Upvotes: 4

Related Questions