Open In App

How to use Async Await with Array.map in TypeScript ?

Last Updated : 19 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

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] 

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.

Syntax:

for (const item of inputArray) {
// asynchronous operation
const result = await someAsyncFunction(item);
// results
resultArray.push(result);
}
return resultArray;

Example: The below example demonstrates the use of async awaits with Array.map using for…of Loop.

Javascript
async function asyncFn(userIn: number): Promise<number> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(userIn * 2);
    }, 1000);
  });
}
async function approach2Fn(inpArr: Array<number>): 
    Promise<Array<number>> {
  const pArr = inpArr.map(async (item) => {
    return asyncFn(item);
  });
  const resArr: Array<number> = [];
  for (const promise of pArr) {
    const res = await promise;
    resArr.push(res);
  }
  return resArr;
}
const arr = [1, 2, 3];
approach2Fn(arr).then((res) => {
  console.log(res);
});

Output:

[2, 4, 6]

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.

Syntax:

async function asyncMap<T, R>(array: T[], asyncCallback: (
item: T, index: number, array: T[]) => Promise<R>): Promise<R[]> {
const results: R[] = [];
for (let i = 0; i < array.length; i++) {
const result = await asyncCallback(array[i], i, array);
results.push(result);
}
return results;
}

Example: IOn this example we defines an asyncMap function to sequentially apply async callbacks to an array, then doubles numbers in an array using it.

JavaScript
async function asyncMap<T, R>(array: T[], asyncCallback: (
    item: T, index: number, array: T[]) => Promise<R>): Promise<R[]> {
  const results: R[] = [];
  for (let i = 0; i < array.length; i++) {
    const result = await asyncCallback(array[i], i, array);
    results.push(result);
  }
  return results;
}

(async () => {
  const numbers = [1, 2, 3, 4, 5];
  const doubled = await asyncMap(numbers, async (num) => {
    return num * 2;
  });
  console.log(doubled); 
})();

Output:

[2, 4, 6, 8, 10]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads