patternjavascriptCritical
Use async await with Array.map
Viewed 0 times
arraywithawaituseasyncmap
Problem
Given the following code:
which produces the following error:
TS2322: Type 'Promise[]' is not assignable to type 'number[]'.
Type 'Promise is not assignable to type 'number'.
How can I fix it? How can I make
var arr = [1,2,3,4,5];
var results: number[] = await arr.map(async (item): Promise => {
await callAsynchronousOperation(item);
return item + 1;
});which produces the following error:
TS2322: Type 'Promise[]' is not assignable to type 'number[]'.
Type 'Promise is not assignable to type 'number'.
How can I fix it? How can I make
async await and Array.map work together?Solution
The problem here is that you are trying to
When the object passed to
What you probably want to do is call
According to the MDN docs for
The
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:
This will resolve the specific error you are encountering here.
Depending on exactly what it is you're trying to do you may also consider using
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 probably want to do 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 resolveswhen 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.
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.Code Snippets
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;
}));Context
Stack Overflow Q#40140149, score: 1240
Revisions (0)
No revisions yet.