2013-07-17 19 views
4

我在寫幾個函數,這些函數是依賴於其他延遲對象的不同組合的有效延遲對象。如何使一個jQuery延期對象解決/拒絕與另一個延期相同的「已解決/被拒絕」狀態?

function takesOneSecond() { 
    return $.Deferred(function(deferred) { 
     // Does something... 
    }).promise(); 
} 

function takesOneMinute() { 
    return $.Deferred(function(deferred) { 
     // Does something... 
    }).promise(); 
} 

function takesThreeMinutes() { 
    return $.Deferred(function(deferred) { 
     // Does something... 
    }).promise(); 
} 

function mySwitchingFunction() { 

    return $.Deferred(function(deferred) { 

     // Does something here.. 
     // Effectively chooses one of several other functions to call. 

     if(/* choose 1 second */) { 

      // We tie ourselves to the '1 second' function. 

      // Call that function. 
      takesOneSecond().done(function() { 

       deferred.resolve(); // If that's done, I'm done too. 

      }).fail(function() { 

       deferred.reject(); // If that failed, I've failed too. 

      }); 

     } else if(/* choose 1 minute */) { 

      // Etc.. 

     } else if(/* choose 3 minutes */) { 

      // Etc.. 

     } 

    }).promise(); 

} 

我寫這個代碼片段很多,有沒有其他辦法可以使延期鏡或級聯推遲的另一個相同的「解決」或「拒絕」狀態?

takesOneSecond().done(function() { 
    deferred.resolve(); // If that's done, I'm done too. 
}).fail(function() { 
    deferred.reject(); // If that failed, I've failed too. 
}); 
+0

是使用$。何時結合延期對象你在找什麼? – BNL

+0

如果你寫這種模式很多,我會說你在做一些嚴重錯誤的事情,應該重新思考你的邏輯。 – adeneo

+0

@adeneo:你能指出一些具體的東西嗎?這基本上是在一系列健全檢查的最後。在檢查結束時,根據檢查結果調用幾個函數中的一個函數(每個函數都是延遲的)。你有推薦的特定模式嗎? –

回答

1

我認爲你根本不需要構建一個新的承諾。只需返回第一個承諾。

function mySecondFunction() { 
    // Does something here.. 
    // Effectively chooses one of several other functions to call. 
    // In this case, assume I've just chosen the 'myFirstFunction' function. 

    // Call that function and return its promise 
    return myFirstFunction(); 
} 

如果你想強調的「在同一時間」的一部分,但可能具有不同的值來解決,你可以只用.then鏈接創建一個新:

function mySecondFunction() { 
    return myFirstFunction().then(function(resultOfFirst) { 
     // but ignore it and 
     return differentResult; 
    }); // errors will propagate automatically 
} 
+0

D'oh。我想你是正確的。這很明顯,現在我就這樣想。這並不能幫助我打算使用它的所有情況,但它對於更簡單的場景肯定會起作用。謝謝。 –

1

我想你可能不瞭解承諾。使用承諾的方法(jQuery < 1.8中的管道),您可以返回新的承諾等。這就是你建立承諾鏈的方式。

下面是一些例子,它類似於你想做什麼:

function returnOne() { 
    return $.Deferred(function(dfr) { 
    dfr.resolve(1); 
    }).promise(); 
} 

// Number will be the result of the original Deferred/Promise 
function addTwo(num) { 
    return $.Deferred(function(dfr) { 
     dfr.resolve(num + 2); 
    }).promise(); 
} 

returnOne().then(addTwo).then(function(result) { 
    // Will be 3 
    console.log(result); 
}); 

根據這種邏輯,你可以過濾你的承諾的分辨率或拒絕不過你想要的,包括剛剛重新解析或拒絕相同的價值,但也許做一些中間工作