Use async await with Array.map

前端 未结 5 2022
臣服心动
臣服心动 2020-11-22 14:42

Given the following code:

var arr = [1,2,3,4,5];

var results: number[] = await arr.map(async (item): Promise => {
        await callAsynchr         


        
5条回答
  •  北海茫月
    2020-11-22 15:35

    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.

    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[].

    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 awaiting it.

    According to the MDN docs for Promise.all:

    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.

    So in your case:

    var arr = [1, 2, 3, 4, 5];
    
    var results: number[] = await Promise.all(arr.map(async (item): Promise => {
        await callAsynchronousOperation(item);
        return item + 1;
    }));
    

    This will resolve the specific error you are encountering here.

提交回复
热议问题