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