Node.js Q承诺,为什么在使用this()时使用defer()?

Red*_*dro 6 javascript callback node.js promise deferred

我想做的事情如下:

somePromiseFunc(value1)
.then(function(value2, callback) {
    // insert the next then() into this function:
    funcWithCallback(callback);
})
.then(function(dronesYouAreLookingFor){
    // Have a party
})
.done();
Run Code Online (Sandbox Code Playgroud)

它没用.我无法让它发挥作用.我被建议defer()用于此目的.

他们自己的文档说我们应该将延迟用于回调式函数.虽然这很令人困惑,因为他们着名的金字塔例子都是关于回调的,但这个例子太抽象了.

因此,我看到很多人使用defers,这就是我所做的:

somePromiseFunc(value1)
.then(function(value2) {
    var promise = q.defer();

    funcWithCallback(function(err, dronesYouAreLookingFor){
        if (!err)
            promise.resolve(dronesYouAreLookingFor);
        else
            promise.reject(new Error(err));
    });
    return promise.promise;
})
.then(function(dronesYouAreLookingFor){
    // Have a party
})
.done();
Run Code Online (Sandbox Code Playgroud)

直到我通过检查源代码发现这也有效:

somePromiseFunc(value1)
.then(function(value2) {
    return function() {
        funcWithCallback(arguments[1]);
    };
})
.then(function(dronesYouAreLookingFor){
    // Have a party
})
.done();
Run Code Online (Sandbox Code Playgroud)

为什么我不能使用这个更简单的无证版本?

没有记载,因为虽然这看起来像金字塔所做的那样,return function(){withCB(arguments[1])}但是return function(err, cb){withCB(cb)}没有.

For*_*say 9

这不是使用promise库的合法方式.正如Q旨在遵守的承诺规范中所详述的那样,从非回应的.then回调中返回的任何内容都应该直接传递.

基本上基于回调的代码应当被视为legacy使用promises时.

你有两个基本选择.如果您多次使用funcWithCallback,您可以执行以下操作:

var promisedFunc = Q.nfbind(funcWithCallback);

somePromiseFunc(value1)
.then(function(value2) {
    return promisedFunc();
})
.then(function(dronesYouAreLookingFor){
    // Have a party
})
.done();
Run Code Online (Sandbox Code Playgroud)

或者如果你需要传递参数:

var promisedFunc = Q.nfbind(funcWithCallback);

somePromiseFunc(value1)
.then(function(value2) {
    return promisedFunc(value1, value2);
})
.then(function(dronesYouAreLookingFor){
    // Have a party
})
.done();
Run Code Online (Sandbox Code Playgroud)

如果你只是一次使用它就可以了

somePromiseFunc(value1)
.then(function(value2) {
    return Q.nfcall(funcWithCallback);
})
.then(function(dronesYouAreLookingFor){
    // Have a party
})
.done();
Run Code Online (Sandbox Code Playgroud)

或者如果你需要传递参数:

somePromiseFunc(value1)
.then(function(value2) {
    return Q.nfcall(funcWithCallback, value1, value2);
})
.then(function(dronesYouAreLookingFor){
    // Have a party
})
.done();
Run Code Online (Sandbox Code Playgroud)