使用Typescript中的数组迭代来简化async-await
有没有一种简单的方法可以在Typescript中表达这种语法,而无需Promise.all
和Array.prototype.map
?
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);
});
ES5数组方法不完全支持async
和生成器函数,这就是为什么for
和其他循环语句应优先于forEach
在ES6中.
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.
在这种情况下,map
被部分滥用,因为它不管理数组值.如果应并行解决承诺,则可能应该是:
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;
});
没有那么简单,但在语义上可能是正确的.如果do..
函数将item
修改为其类型更改的点,则const newItems = await Promise.all(...)
也可以更轻松地管理项目类型.
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.
如果应该依次解决这些问题,而不必涉及Promise.all
,则可以为for..of
:
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);
});