Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define the callback in the Async library's "Each" function?

In Caolan's Async library, the documentation says that the each function:

Applies the function iteratee to each item in arr, in parallel. The iteratee is called with an item from the list, and a callback for when it has finished.

This example is given:

async.each(arr, iteraree, function(err){
    //Do stuff
});

My question is how is the "callback", in this case iteraree, defined? How do you declare which callback function you would like called when it has finished?

If you were able to define functions as a parameter I could see it working but you can't (i.e):

async.each(openFiles, function (item, function () {console.log("done")}), function(err){
  //Do stuff
});

But how could I define that callback not inline?

If I do something like

var iteraree = function (item, callback) {};

And passed in iteraree I still do not see where I would be able to define the behavior of callback.

like image 825
Startec Avatar asked Mar 24 '26 21:03

Startec


2 Answers

I still do not see where I would be able to define the behavior of callback.

You don't. callback is just a parameter. async.each calls iteratee and passes a value for callback. It's your responsibility to call callback when you are done. This lets async.each know that it can continue to the next iteration.


function (item, function () {console.log("done")}) is invalid JavaScript btw. You cannot have a function definition in place of a parameter.

like image 133
Felix Kling Avatar answered Mar 26 '26 11:03

Felix Kling


That iteratee function doesn't have the signature you think it does. It looks like this:

async.each(openFiles, function (item, cb){
       console.log(item);
       cb();   
    }, function(err){
      //Do stuff
 });

It receives each item and a callback function from asynchronous.each() that has to be called when you finish whatever you are doing. You don't provide the callback.

So if you are using a named function it's just:

 function foo (item, cb){
       console.log(item);
       cb();   
    }

async.each(openFiles, foo, function(err){
      //Do stuff
 });
like image 39
Robert Moskal Avatar answered Mar 26 '26 10:03

Robert Moskal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!