2013-03-20 74 views
6

我有一個jQuery 1.9.1承諾的問題,其中我可能需要條件邏輯將返回另一個延遲,我不知道如何處理它。這是我最好的嘗試,但正如下面的註釋所表明的那樣,當我點擊else分支時,我仍然擊中了第二個.then()函數,我希望我可以返回給用戶。如何處理這種情況的任何模式?處理具有承諾的分支

storage.provision(c) 

.then(function(rc){ 
    if(rc === 0){ 
     storage.write(c); 
    }else{ 
     return options.onSuccess(rc); //how i got back to the users callbacks/promise, but this 
     //takes me to the .then below 
    } 
}) 
//storage.write returns a promise as well, do I do another .then 
// like this? 
.then(function(rc){ 
    //I was hoping this would catch, the storage.write() case, and it does, but it also catches 
    //the retun options.onSuccess(rc) in the else case. 
    options.onSuccess(rc); 
}) 


.fail(function(e){ 
    //handle error using .reject() 
}); 
+0

這篇文章可能會幫助你:http://stackoverflow.com/questions/12149993/attempting-to-break-jquery-promise-chain-with-then-fail-and-reject – mattytommo 2013-03-20 21:16:34

+0

[This post](http: //net.tutsplus.com/tutorials/javascript-ajax/wrangle-async-tasks-with-jquery-promises/)可以幫助你更好地理解承諾。一般情況下,如果你想使用條件,你應該將promise保存爲一個變量,然後在你的條件中執行你的'then''成功或'失敗',你似乎正在反其道而行。 – acconrad 2013-03-20 21:28:36

回答

4

這成爲通過取options.onSuccess(rc);被無條件地執行在第二.then()但從來沒有在第一視圖更容易。

因此,第一.then()必須通過上rc任一:

  • 如果rc === 0,響應於storage.write(c)完成
  • 或如果立即rc !== 0

.then()是這真的是方便,因爲它允許自然要麼從其done回調函數返回了一個新的承諾的價值。

storage.provision(c).then(function(rc) { 
    if(rc === 0) { 
     var dfrd = $.Deferred(); 
     storage.write(c).done(function() { 
      dfrd.resolve(rc); 
     }).fail(dfrd.fail); 
     return dfrd.promise(); 
    } else { 
     return rc;//pass on rc to the second .then() 
    } 
}).then(function(rc){ 
    options.onSuccess(rc); 
}).fail(function(e){ 
    //handle error using .reject() 
}); 

我確定存在其他方法,但這是最接近我能想到的最初的概念。

這將是很好不是要創建一個新的時rc === 0但它是傳遞rc,避免了需要修改storage.write()以這種方式來表現的最現實的方法遞延。