Home >Web Front-end >JS Tutorial >How to Resolve 'Type 'Promise[]' is not assignable to type 'number[]'' When Using Async/Await with Array.map?

How to Resolve 'Type 'Promise[]' is not assignable to type 'number[]'' When Using Async/Await with Array.map?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 01:04:09858browse

How to Resolve

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[]' is not assignable to type 'number[]'. Type 'Promise' is not assignable to type 'number'."

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[]' is not assignable to type 'number[]'" error.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn