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?
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.
Quoting from the async.each
documentation:
iterator(item, callback)
- A function to apply to each item inarr
. The iterator is passed acallback(err)
which must be called once it has completed. If no error has occurred, the callback should be run without arguments or with an explicitnull
argument.
Conclusion: You forgot to take the callback parameter and therefore did not call it either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With