How to use Promise.all and Array.map In Typescript
In this approach, we are using Promise.all and Array.map where the asynchronous function (asyncFn) is applied to each of the input array elements using the Promise.all and Array.map method. This results in an array of all the resolved promises.
Syntax:
const res = await Promise.all(array.map(async (item) => await asyncFunction(item)));
Example: The below example demonstrates the use of async await with Array.map using Promise.all and Array.map.
async function asyncFn(item: number): Promise<number> {
return new Promise(
resolve => setTimeout(() =>
resolve(item * 2),
1000));
}
async function arrFn(array: number[]): Promise<number[]> {
const res =
await Promise.all(array.map(asyncFn));
return res;
}
const userInp = [1, 2, 3, 4];
arrFn(userInp).then(output =>
console.log(output));
Output:
[2, 4, 6, 8]
How to use Async Await with Array.map in TypeScript ?
In this article, we will learn how we can use async wait with Array.map() method in TypeScript. In TypeScript, the async and await are mainly used to work with asynchronous tasks. Using this we can write the code that consists of the tasks that take time to complete like reading the file, fetching data from the server, etc.
There are two approaches through which we can use async await with Array.map.
Table of Content
- Using Promise.all and Array.map
- Using for…of Loop
- Custom Async Mapping Function