将异步等待与 Array.map 一起使用 [英] Use async await with Array.map
问题描述
给定以下代码:
var arr = [1,2,3,4,5];
var results: number[] = await arr.map(async (item): Promise<number> => {
await callAsynchronousOperation(item);
return item + 1;
});
产生以下错误:
TS2322:类型Promise
TS2322: Type 'Promise<number>[]' is not assignable to type 'number[]'. Type 'Promise<number> is not assignable to type 'number'.
我该如何解决?如何让 async await
和 Array.map
一起工作?
How can I fix it? How can I make async await
and Array.map
work together?
推荐答案
这里的问题是你试图await
一个承诺数组而不是一个承诺.这不符合您的预期.
The problem here is that you are trying to await
an array of promises rather than a Promise. This doesn't do what you expect.
当传递给 await
的对象不是 Promise 时,await
只是立即按原样返回值,而不是尝试解析它.因此,由于您在 await
此处传递了一个(由 Promise 对象组成的)数组而不是 Promise,因此 await 返回的值只是该数组,其类型为 Promise
When the object passed to await
is not a Promise, await
simply returns the value as-is immediately instead of trying to resolve it. So since you passed await
an array (of Promise objects) here instead of a Promise, the value returned by await is simply that array, which is of type Promise<number>[]
.
您可能想要做的是在 map
返回的数组上调用 Promise.all
以便在 await之前将其转换为单个 Promise编码>它.
What you probably want to do is call Promise.all
on the array returned by map
in order to convert it to a single Promise before await
ing it.
Promise.all(iterable)
方法返回一个可解析的承诺当可迭代参数中的所有承诺都已解决时,或拒绝的原因是第一个通过的承诺拒绝.
The
Promise.all(iterable)
method returns a promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first passed promise that rejects.
所以在你的情况下:
var arr = [1, 2, 3, 4, 5];
var results: number[] = await Promise.all(arr.map(async (item): Promise<number> => {
await callAsynchronousOperation(item);
return item + 1;
}));
这将解决您在此处遇到的特定错误.
This will resolve the specific error you are encountering here.
根据您想要做什么,您也可以考虑使用 Promise.allSettled
, Promise.any
或 Promise.race
而不是 Promise.all
,尽管在大多数情况下(几乎可以肯定包括这个)Promise.all
将是你想要的.
Depending on exactly what it is you're trying to do you may also consider using Promise.allSettled
, Promise.any
, or Promise.race
instead of Promise.all
, though in most situations (almost certainly including this one) Promise.all
will be the one you want.
这篇关于将异步等待与 Array.map 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!