Bird Eggegg
Bird Eggegg

Reputation: 449

async.each() final callback is not executed

async.each(spiders, function(){
    console.log('hi');
}, function(err) {
    if(err) { console.log(err);}
    else console.log('ok');
});

After logging 'hi', async didn't execute the callback and logged 'ok' or errors.

What is wrong in my code?

Upvotes: 4

Views: 4300

Answers (2)

miklosme
miklosme

Reputation: 791

async provides two important parameters to your iterator function: an item and a callback. The first one gives you the actual data item from the array, and the second is a function, to indicate the end of the actual method. The final callback (the one with the log('ok')) gets called, when every iterator call indicated their own callback.

So your code should be something like this:

async.each(spiders, function(item, callback) {
  console.log('spider: ' + item);
  callback(null);
}, function(err) {
  if (err) {
    return console.log(err);
  }
  console.log('ok');
});

The null parameter means there is no error.

Also note, handling error like this, is a better practice.

Upvotes: 15

TimWolla
TimWolla

Reputation: 32691

Quoting from the async.each documentation:

iterator(item, callback) - A function to apply to each item in arr. The iterator is passed a callback(err) which must be called once it has completed. If no error has occurred, the callback should be run without arguments or with an explicit null argument.

Conclusion: You forgot to take the callback parameter and therefore did not call it either.

Upvotes: 2

Related Questions