Loop through asynchronous request

You can use async module which will be really helpful to you for making requests one by one. Below is a sample code from async official docs which is fairly intuitive to understand.

  function asyncForEach (arr, iterator, callback) {
    queue = arr.slice(0)
        // create a recursive iterator
    function next (err) {
      if (err) return callback(err)

            // if the queue is empty, call the callback with no error
      if (queue.length === 0) return callback(null)

            // call the callback with our task
            // we pass `next` here so the task can let us know when to move on to the next task
      iterator(queue.shift(), next)
    }

        // start the loop;
    next()
  }

function sampleAsync (param, done) {
// put a callback when function is done its work 
}

  asyncForEach(result, function (param, done) { // result is the array you pass as iterator
    sampleAsync(param, function (message) {
      console.log(message)
      done()
    })
  }, function () {
    console.log('callback')
    callback(SOME_RESULT)
  })

}

Leave a Comment