连锁回调的最佳方式?

P B*_*rke 7 node.js

我有一个关于在回调之间传递数据时将回调链接在一起的最佳方法的问题。我下面有一个示例,它可以工作,但有一个缺陷,即函数必须了解链并知道它们的位置/是否传递回调。

\n\n
function first(data, cb1, cb2, cb3){\n    console.log("first()", data);\n    cb1(data,cb2, cb3);\n}\nfunction second(data, cb1, cb2) {\n    console.log("second()",data);\n    cb1(data, cb2);\n}\nfunction third(data, cb) {\n    console.log("third()",data);\n    cb(data);\n}\nfunction last(data) {\n    console.log("last() ", data);\n}\nfirst("THEDATA", second, third, last);  // This work OK\nfirst("THEDATA2", second, last);        // This works OK\nfirst("THEDATA3", second);              // This doesn\'t work as second tries to pass on a callback that doesn\'t exit.\n
Run Code Online (Sandbox Code Playgroud)\n\n

我可以想出很多方法来解决这个问题,但它们都涉及让被调用的函数了解正在发生的事情。但我的问题是,我\xe2\x80\x99m 处理的实际函数已经存在,如果可以避免的话,我不想修改它们。所以我想知道我是否错过了如何调用这些的技巧?

\n

P B*_*rke 5

感谢您的回答,我同意 Promise 可能是最合适的解决方案,因为它们满足我的要求并提供了许多其他优势。

不过,我也想出了如何在不涉及任何额外模块的情况下做我想做的事情。

回顾一下具体要求是:

  • 通过回调将多个函数链接在一起(这样第一个函数可以使用其他函数所依赖的非阻塞 I/O 调用),
  • 在它们之间传递参数(数据)时,以及
  • 无需修改现有函数即可了解它们在回调链中的位置。

我缺少的“技巧”是引入一些额外的匿名回调函数来充当现有函数之间的链接。

// The series of functions now follow the same pattern, which is how they were before
// p1 data object and p2 is a callback, except for last().
function first(data, cb){
    console.log("first()", data);
    cb(data);
}
function second(data, cb) {
    console.log("second()",data);
    cb(data);
}
function third(data, cb) {
    console.log("third()",data);
    cb(data);
}
function last(data) {
    console.log("last() ", data);
}

// And the named functions can be called pretty much in any order without 
// the called functions knowing or caring. 

// first() + last()
first("THEDATA", function (data) { // The anonymous function is called-back, receives the data, 
    last(data);                    // and calls the next function.
});

// first() + second() + last()
first("THEDATA2", function (data) {
    second(data, function (data){
        last(data);
    }); // end second();
}); // end first();

// first() + third()! + second()! + last()
first("THEDATA3", function (data) {
    third(data, function (data){
        second(data, function (data){
            last(data);
        }); // end third();
    }); // end second();
}); // end first();
Run Code Online (Sandbox Code Playgroud)