【问题标题】:How do I chain on another callback function in Node.js?如何在 Node.js 中链接另一个回调函数?
【发布时间】:2012-05-03 14:34:33
【问题描述】:

我有一个 node.js 函数:

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

如果我无论如何都无法编辑此功能,我如何知道它何时完成。有没有办法将另一个回调函数链接到它上面。无论如何都无需编辑 myFunc。

即如果我正在使用:

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

我把什么作为迭代器?

我如何知道所有 myFunc 都已执行时传递控制权?

【问题讨论】:

    标签: node.js asynchronous callback chaining


    【解决方案1】:

    类似:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-07
        • 2018-04-10
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-23
        • 1970-01-01
        相关资源
        最近更新 更多