Javascript provide  the map function to iterate through array of items or objects. We can return new item from the callback function for each item to create brand new array with new properties or transformed it into different structure.  Mostly we use map to for transformation. 

In some case, we need to perform async operation on each item on the array. For example, we have list of userId, firstName and lastName in an array.  Let’s write a sample code to perform API call for each item in the array with simple map function.

const users = [
  {
    userId: 1,
    firstName: 'John',
    lastName: 'Doe',
  },
  {
    userId: 2,
    firstName: 'Jane',
    lastName: 'Doe',
  },
  {
    userId: 2,
    firstName: 'Alice',
    lastName: 'Henderson',
  },
]

 users.map( user => {
  const result = await api.post(url, user);
  return result
})

In above code all three request will be initiated  immediately. Map function don’t await for each request to resolve rather it return pending promise and  execute all request.  In some cases API call may be blocked because of too many request. If you are doing db operation then multiple db connection will be open at a time which might cause an error. To avoid a parallel execution, load and error, we can serialize the map and execute it one at a time. 

There are multiple way to achieve this, but in this article we will explore a library call `async`  which provide the method call `mapSeries`  that can  serialize the async loop.
 

Let’s re-write the above code with the with mapSeries function.


import mapSeries from 'async/mapSeries';

const users = [
  {
    userId: 1,
    firstName: 'John',
    lastName: 'Doe',
  },
  {
    userId: 2,
    firstName: 'Jane',
    lastName: 'Doe',
  },
  {
    userId: 2,
    firstName: 'Alice',
    lastName: 'Henderson',
  },
]

const result = mapSeries(users, async(user)=>{
  const response = await api.post(url, user);
  return result
})

// result will be an array of response from each api call respond.

 

mapSeries function will take two argument array of item and function that  need to be executed for each item in the array.  

Note: mapSeries take third optional argument , callback  which will be called once the execution is completed.  If callback is not passed then it will return a promise.

Async library provide various method also which can executed two request or variable number of request in parallel. Please check import `mapValuesLimit` and official documentation for more . And iteratee should always be an async function.