Aron Woost Aron Woost -4 years ago 118
Javascript Question

Whats the smartest / cleanest way to iterate async over arrays (or objs)?

Thats how I do it:

function processArray(array, index, callback) {
processItem(array[index], function(){
if(++index === array.length) {
callback();
return;
}
processArray(array, index, callback);
});
};

function processItem(item, callback) {
// do some ajax (browser) or request (node) stuff here

// when done
callback();
}

var arr = ["url1", "url2", "url3"];

processArray(arr, 0, function(){
console.log("done");
});


Is it any good? How to avoid those spaghetti'ish code?

Answer Source

Checkout the async library, it's made for control flow (async stuff) and it has a lot of methods for array stuff: forEach, filter, map. Check the documentation on github. Here's what you probably need:

forEach(arr, iterator, callback)

Applies an iterator function to each item in an array, in parallel. The iterator is called with an item from the list and a callback for when it has finished. If the iterator passes an error to this callback, the main callback for the forEach function is immediately called with the error.

forEachSeries(arr, iterator, callback)

The same as forEach only the iterator is applied to each item in the array in series. The next iterator is only called once the current one has completed processing. This means the iterator functions will complete in order.

Update - the functions are now called each and eachSeries

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download