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]


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