使用Typescript中的数组迭代来简化async-await [英] Simplify async-await with array iteration in Typescript

查看:173
本文介绍了使用Typescript中的数组迭代来简化async-await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法可以在Typescript中表达这种语法,而无需Promise.allArray.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);
});

这篇关于使用Typescript中的数组迭代来简化async-await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆