Search code examples
node.jsasynchronouscallbackchaining

How do I chain on another callback function in Node.js?


I have a node.js function:

function myFunc(callback) {
    var ret = 50; // some time consuming calculation 
    return callback(random);
}

How do I know when this function has completed if I can't edit it in anyway. Is there a way to chain another callback function onto it. Again without editing myFunc in anyway.

i.e. if I am using:

async.forEach([1, 2, 3], function iter(myFunc(console.log), ????) {}, function(err){
    // if any of the saves produced an error, err would equal that error
});

What do I put as the iterator?

How do I know pass on control when all the myFuncs have executed?


Solution

  • Something like :

    // fn wraps myFunc
    var fn = function(callback) {
        // myFunc isn't altered, it is called with callback function
        myFunc(function(random) {
           console.log('done');
           callback(random);
        };
    };
    
    async.forEach([1,2,3], fn(console.log));