Node.js - Using the async lib - async.foreach with object

Ben picture Ben · Apr 30, 2012 · Viewed 74.8k times · Source

I am using the node async lib - https://github.com/caolan/async#forEach and would like to iterate through an object and print out its index key. Once complete I would like execute a callback.

Here is what I have so far but the 'iterating done' is never seen:

    async.forEach(Object.keys(dataObj), function (err, callback){ 
        console.log('*****');

    }, function() {
        console.log('iterating done');
    });  
  1. Why does the final function not get called?

  2. How can I print the object index key?

Answer

stewe picture stewe · Apr 30, 2012

The final function does not get called because async.forEach requires that you call the callback function for every element.

Use something like this:

async.forEach(Object.keys(dataObj), function (item, callback){ 
    console.log(item); // print the key

    // tell async that that particular element of the iterator is done
    callback(); 

}, function(err) {
    console.log('iterating done');
});