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.

Javascript
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

Similar Reads

Using Promise.all and Array.map

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

Using for…of Loop

In this approach, we have the async function which represents the asynchronous operation and the apporach2Fn function which uses the Array.map to create an array of promises by applying asyncFn to each element of the array. Then we are using the for…of the loop to iterate over this array of promises using await to collect the asynchronous results and display them....

Custom Async Mapping Function

In certain scenarios, a custom async mapping function can offer more flexibility and control over asynchronous operations within arrays. This custom approach involves defining a function that iterates over the array asynchronously, awaiting each operation individually....

Contact Us