Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 226
Bird Eggegg Avatar asked Dec 05 '22 03:12

Bird Eggegg


2 Answers

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.

like image 184
miklosme Avatar answered Dec 27 '22 10:12

miklosme


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.

like image 34
TimWolla Avatar answered Dec 27 '22 12:12

TimWolla