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

陌路散爱 提交于 2019-12-12 01:57:37

问题


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?


回答1:


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));



回答2:


myFunc(function(ret) {
  console.log("finished");
  console.log(ret);
});


来源:https://stackoverflow.com/questions/10272797/how-do-i-chain-on-another-callback-function-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!