给定以下代码:

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'。

我该怎么解决呢?我如何使异步等待和数组。地图一起工作?


当前回答

这是最简单的方法。

await Promise.all(
    arr.map(async (element) => {
        ....
    })
)

其他回答

这是最简单的方法。

await Promise.all(
    arr.map(async (element) => {
        ....
    })
)

使用modern-async's map()的解决方案:

import { map } from 'modern-async'

...
const result = await map(myArray, async (v) => {
    ...
})

使用该库的优点是可以使用mapLimit()或mapSeries()控制并发性。

你可以使用:

for await (let resolvedPromise of arrayOfPromises) {
  console.log(resolvedPromise)
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

如果你想使用Promise.all(),你可以使用promise . allsettle () 所以你可以更好地控制被拒绝的承诺。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

我在BE方面有一个任务,从回购中找到所有实体,并添加一个新的属性url并返回到控制器层。这就是我如何做到的(感谢Ajedi32的回应):

async findAll(): Promise<ImageResponse[]> {
    const images = await this.imageRepository.find(); // This is an array of type Image (DB entity)
    const host = this.request.get('host');
    const mappedImages = await Promise.all(images.map(image => ({...image, url: `http://${host}/images/${image.id}`}))); // This is an array of type Object
    return plainToClass(ImageResponse, mappedImages); // Result is an array of type ImageResponse
  }

注意:Image(实体)没有属性url,但imagerresponse -有

解决方案下面正确使用异步等待和数组。地图在一起。并行、异步处理数组中的所有元素,并保持顺序:

Const arr = [1,2,3,4,5,6,7,8]; const randomDelay = () => new Promise(resolve => setTimeout(resolve, Math.random() * 1000)); Const calc = async n => { 等待randomDelay (); 返回n * 2; }; const asyncFunc = async() => { const unresolvedPromises = arr.map(calc); const results = await Promise.all(未解决的promise); document . write(结果); }; document . write(“计算…”); asyncFunc ();

也codepen。

注意,我们只“等待”Promise.all。我们多次调用没有“await”的calc,并立即收集一组未解决的承诺。然后承诺。All等待解析所有这些值,并返回一个包含已解析值的数组。