Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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) {});
share|improve this answer
    
Oh ok that works perfectly! I assumed from the documentation that the callback had to be invoked before the wrapper function ended –  Colin Aug 13 '13 at 5:22
    
Nope, it could be 10 layers deep for all async cares. And if it never gets called at all, async will just wait forever. –  Peter Lyons Aug 13 '13 at 5:25
    
Awesome! That does make things easy! Thanks for your time –  Colin Aug 13 '13 at 15:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.