4
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?

1
  • 1
    You want to use a asynchronous forEach or _.each Commented May 10, 2015 at 13:34

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.