3

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);
});
7
  • No. Why do you think it is not simple enough? Commented May 16, 2018 at 18:24
  • If you want to do all of the promises concurrently you have to use Promise.all Commented May 16, 2018 at 18:24
  • i thought it was just a lot of ceremony and overhead to remember to use .map Commented May 16, 2018 at 18:25
  • @DanielA.White I don't think typescript has any kind of array comprehensions Commented May 16, 2018 at 18:25
  • @DanielA.White What would you have used but map to create the array of promises? Commented May 16, 2018 at 18:26

1 Answer 1

4

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.