Colin
Colin

Reputation: 1855

Using async with asynchronous functions

I know this sounds stupid, but I can't understand how to use async to handle existing asynchronous functions.

For example, consider some asynchronous function foo(arg1, arg2, ..., argN, callback) defined in some node module. Say I want to use this in async's waterfall(tasks,[callback]) function. How could I possibly do this?

//original call
foo(x1,x2,xN, function goo(err, res) {
    // do something 
});

//using async
async.waterfall([
   function(callback) {
       foo(x1,x2,...,xN, callback);
   }
], function goo(err, res) {
   // do something
}); 

but I can't do that since callback needs to be called before the end of the function. Help?

Upvotes: 1

Views: 146

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146164

Yup, what you have will work. callback just tells async, "I'm done, go to the next". You can also use async.apply to generate those little wrapper functions automatically:

async.waterfall([
  async.apply(foo, x1, x2, nX) //don't use callback, async will add it,
  someOtherFunction
], function (error, finalResult) {});

Upvotes: 3

Related Questions