簡體   English   中英

Node.js Q承諾,為什么在使用this()時使用defer()?

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

我想做的事情如下:

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

它沒用。 我無法讓它發揮作用。 我被建議為此目的使用defer()

他們自己的文檔說我們應該將延遲用於回調式函數。 雖然這很令人困惑,因為他們着名的金字塔例子都是關於回調的,但這個例子太抽象了。

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

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)}卻沒有。

這不是使用promise庫的合法方式。 正如Q旨在遵守的承諾規范中所詳述的那樣,您從.then回調中返回的任何非承諾的內容都應該直接通過。

當您使用promises時,基本上基於回調的代碼應被視為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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM