Simplify async-await with array iteration in Typescript

拜拜、爱过 提交于 2019-12-23 16:04:41

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/50377665/simplify-async-await-with-array-iteration-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!