0

What is the best way to call a callback function after completion of an async call for all elements of array, from within a for loop?

Currently I am checking for iterator to match length of array as follows, but I want to know if there is a better way.

exports.myFunction = function (arr, callback) {
    for (var i = 0; i < arr.length; i++) {
        (function (i) {
            var comp = arr[i];

            // do other calculations

            // call an async function
            asyncOperation(comp, function(response){
                // further changes in response here

                // if last array element, call callback()
                if (i == arr.length - 1) {
                    // call the callback...
                    callback();
                }
            });
        })(i);
    }
}

Can you please suggest the best approach for this kind of situation?

mynawaz
  • 1,599
  • 1
  • 9
  • 16
  • Try checking out the [async](https://github.com/caolan/async) module. – whitfin Oct 06 '15 at 09:03
  • @zackehh: Please, no more. – Madara's Ghost Oct 06 '15 at 09:03
  • @MadaraUchiha what's wrong with that lib? It's a useful shortcut for this type of thing, and it's pretty widely used. – whitfin Oct 06 '15 at 09:04
  • 2
    @zackehh: We have promises natively now. Callback based operations are on the decline, and the `async` module is basically a collection of hacks to overcome inherent callback limitations which are trivially solved with Promises. – Madara's Ghost Oct 06 '15 at 09:05
  • Hm, this may be a better dupe: http://stackoverflow.com/questions/25429522/q-promise-nodejs-how-to-resolve-in-loop – Cerbrus Oct 06 '15 at 09:06
  • @MadaraUchiha disagree. Lots of people dislike the Promise interface, (not to mention several Node.js TSC members). Node.js has extremely limited Promises natively, and even then only if you're on the absolute latest, which most people aren't. Promises are sugar for the exact same thing, yet far harder to understand as a beginner (IMO). – whitfin Oct 06 '15 at 09:07

0 Answers0