据我所知,劳埃德的陈述是正确的,但我认为这并不是您正在寻找的答案,这是我的尝试:
首先,当使用延迟承诺时,唯一合理的期望和作为返回值提供的是承诺对象(因此 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:
});
你会在延迟风格的实现中这样做:
/* 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 的 Q库(以及他提供的优质 README)并在CommonJS wiki上阅读它。克里斯也在 2010 年就这个话题发表了演讲