Home >Web Front-end >JS Tutorial >How to Resolve 'Type 'Promise[]' is not assignable to type 'number[]'' When Using Async/Await with Array.map?
Using Async/Await with Array.map
When attempting to use async/await with Array.map, users frequently encounter an error similar to the following:
"Type 'Promise
This error arises because await functions must resolve a Promise. However, Array.map typically returns an array of Promises instead of a single Promise.
Solution
To address this issue, convert the array of Promises returned by Array.map to a single Promise using Promise.all. Promise.all resolves only when all Promises in its iterable argument have been resolved.
Here's a modified version of the problematic code:
const arr = [1, 2, 3, 4, 5]; const results: number[] = await Promise.all(arr.map(async (item): Promise<number> => { await callAsynchronousOperation(item); return item + 1; }));
By utilizing Promise.all, the array of Promises is resolved as a single Promise, allowing await to function correctly, eliminating the "Type 'Promise
Additional Options
Depending on the specific use case, consider using Promise.allSettled, Promise.any, or Promise.race instead of Promise.all. However, Promise.all is typically the most appropriate choice in situations like the one described above.
The above is the detailed content of How to Resolve 'Type 'Promise[]' is not assignable to type 'number[]'' When Using Async/Await with Array.map?. For more information, please follow other related articles on the PHP Chinese website!