对Array.map使用async await [英] 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< number> []'不能分配给'number []'。
输入'Promise< number>不能指定为'number'类型。
TS2322: Type 'Promise<number>[]' is not assignable to type 'number[]'. Type 'Promise<number> is not assignable to type 'number'.
我该如何解决?如何让异步等待
和 Array.map
一起工作?
How can I fix it? How can I make async await
and Array.map
work together?
推荐答案
这里的问题是你试图等待
一系列承诺而不是承诺。这不符合您的预期。
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返回的值就是那个类型为承诺< number> []
。
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>[]
.
您需要做的是致电 Promise.all
在 map
返回的数组上,以便在 await
之前将其转换为单个Promise。
What you need to do here is call Promise.all
on the array returned by map
in order to convert it to a single Promise before await
ing it.
根据 MDN文档 Promise.all
:
Promise.all(iterable)
方法返回一个promise,当可迭代参数中的所有promise都已解析时,它会解析
,或
因为第一次通过承诺拒绝而拒绝。
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.
这篇关于对Array.map使用async await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!