由劳合社的声明是正确的,据我知道,但我不认为这是正是你要找的答案,这是我的尝试:
首先,与延迟承诺的唯一合理的事情工作时期望并提供作为回报价值的承诺对象(因此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