1

I have an array of items. I want to call an asynchroneous funcion on all of them. When the work is done for all items i want to call other function. I can not use any external libraries.

//array
var items;

for ( var i in items){
// function doAsync supports callback
items[i].doAsync(function callback(){...});
}

I have done it like this, but I am not sure if this is a safe solution:

var items;
var loopsFinished = 0;
for (var i in items) {
    items[i].doAsync(function callback() {
             ...
        loopsFinished++;
        if (loopsFinished == items.length) {
            otherFunction();
        }
    });
}
Marcel
  • 1,084
  • 2
  • 15
  • 28
  • 2
    Aside from [“for…in” usage in array iteration being a bad idea](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea), that pattern should work, as long as you ensure that `loopsFinished` can't be tampered with, and each item can only call `callback` once. – DCoder Mar 02 '14 at 20:22
  • Use `async.forEach` from Async.js: https://github.com/caolan/async – noseratio Mar 02 '14 at 23:47

0 Answers0