由勞合社的聲明是正確的,據我知道,但我不認爲這是正是你要找的答案,這是我的嘗試:
首先,與延遲承諾的唯一合理的事情工作時期望並提供作爲回報價值的承諾對象(因此Lloyd將您指向CPS)。
在那裏你會通常這樣做
/* Have some kind of callback for when ajax is done */
var myCompleteCallback = function(data){
// whatever you want to do with your ajax call results
}
var myErrorCallback = function(){
// handle the ajax error
}
/* Send the actual ajax request, and tell it to call MyCompleteCallback afterwards */
$.ajax({
url: '/foo/bar.xml'
data: {},
success: myCompleteCallback,
error:
});
你會不喜歡這樣的遞延式implementaion:
/* Have some kind of callback for when promise is resolved is done */
var myCompleteCallback = function(data){
// whatever you want to do with your ajax call results
}
var myErrorCallback = function(){
// handle the ajax error
}
/* you could also do ajax.done().fail() but i think this reads better as an example */
var getsomething = $.ajax({ url: '/foo/bar.xml', data: {} });
getsomething.then(myCompleteCallback, myErrorCallback)
所以你看,沒有什麼太多的神奇和不同關於它,除非你開始進入更復雜的例子。
請告訴我冷靜一下吧,雖然(從前面的例子以下)...
var getVisitorInfo = function(){
/* stash the user information ajax call promise */
var fetchUserInfo = $.ajax({url:"/some/api/user.json"})
/* stash the account information ajax call promise */
var fetchAccountInfo = $.ajax({url:"/some/api/user.json"})
/* trigger both calls and returns a promise that will resolve to both results */
return $.when(fetchUserInfo, fetchAccountInfo)
}
/* Usage: */
getVisitorInfo().done(function(userJSON, accountJSON){
// manipulate your data/ui/and whatnot
}).fail(function(failure1,failure2){
// redirect to login or whatever
})
希望這有助於。我建議看看各種延遲/承諾實現,以更好地理解這一切。真正幫助我的是玩Kris Kowal's Q圖書館(以及他提供的高質量自述文件)並在CommonJS wiki上閱讀。而克里斯也給了一個talk on the topic back in 2010