Node.js Q 承诺,当您可以使用 this() 时,为什么要使用 defer()

Node.js Q promises, why use defer() when you can use this()?

本文关键字:为什么 defer js 可以使 Node this 承诺      更新时间:2023-09-26

我想做这样的事情:

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

它没有用。我无法让它工作。我被建议为此目的使用defer()

他们自己的文档说我们应该对回调样式的函数使用延迟。虽然这令人困惑,因为他们著名的扁平金字塔示例都是关于回调的,但该示例太抽象而无法遵循。

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

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

直到我通过检查源代码发现这也可以工作:

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

为什么我不应该使用这个更简单的无文档版本?

没有记录,因为尽管这看起来像是扁平金字塔的作用,但return function(){withCB(arguments[1])}起作用,而return function(err, cb){withCB(cb)}则不起作用。

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

本质上,使用承诺时,应将基于回调的代码视为legacy

您有两个基本选项。 如果你经常使用 funcWithCallback,你可以执行以下操作:

var promisedFunc = Q.nfbind(funcWithCallback);
somePromiseFunc(value1)
.then(function(value2) {
    return promisedFunc();
})
.then(function(dronesYouAreLookingFor){
    // Have a party
})
.done();

或者,如果您需要传递参数:

var promisedFunc = Q.nfbind(funcWithCallback);
somePromiseFunc(value1)
.then(function(value2) {
    return promisedFunc(value1, value2);
})
.then(function(dronesYouAreLookingFor){
    // Have a party
})
.done();

如果您只使用它一次,则可以

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

或者,如果您需要传递参数:

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