给出以下代码:
var arr = [1,2,3,4,5];
var results: number[] = await arr.map(async (item): Promise<number> => {
await callAsynchronousOperation(item);
return item + 1;
});
这会产生以下错误:
TS2322: Type ‘Promise<number>[]’ is not assignable to type ‘number[]’.
Type ‘Promise<number> is not assignable to type ‘number’.
我该如何解决?如何使异步await和Array.map一起工作?
解决方法:
这里的问题是你试图等待一系列的承诺而不是承诺.这不符合您的期望.
当传递给await的对象不是Promise时,await只是立即返回值,而不是尝试解析它.因此,既然你在这里传递了一个数组(Promise对象)而不是Promise,那么await返回的值就是那个类型为Promise< number> []的数组.
你需要做的是在map返回的数组上调用Promise.all,以便在等待之前将其转换为单个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;
}));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。