有没有更简单的方式在Typescript中表达这个语法,而不需要使用Promise.all
和Array.prototype.map
?
const items = [...];
await Promise.all(items.map(async item => {
doSomething(item);
const result = await doSomethingAsync(item);
doSomethingMore(result, item);
});
有没有更简单的方式在Typescript中表达这个语法,而不需要使用Promise.all
和Array.prototype.map
?
const items = [...];
await Promise.all(items.map(async item => {
doSomething(item);
const result = await doSomethingAsync(item);
doSomethingMore(result, item);
});
ES5数组方法不完全支持 async
和 generator 函数,这是为什么在 ES6 中应该优先选择 for
和其他循环语句而不是 forEach
的原因之一。
在这种情况下,map
部分被误用,因为它不管理数组值。如果承诺应该并行解决,可能应该是:
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(...)
也可以更容易地管理项目类型。
如果它们应该按顺序解决,并且不需要涉及Promise.all
,则可以使用for..of
:
for (const item of items) {
doSomething(item);
const result = await doSomethingAsync(item);
doSomethingMore(result, item);
});
Promise.all
。 - Explosion Pills.map
只是一种繁琐的仪式和额外负担。 - Daniel A. Whiteawait items.forEach(async)
。 - Daniel A. Whitemap
和Promise.all
调用组合起来。当你想要并发执行任务时,这是无法避免的。另外,停止使用forEach
,使用for ... of
更符合习惯用法。 - Bergi