据我所知,Lloyd 的陈述是正确的,但我不认为这正是您正在寻找的答案,这是我的尝试:
首先,在使用延迟承诺时,唯一合理的期望和作为返回值提供的是承诺对象(因此 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's Q 库(以及他提供的优质自述文件)并在CommonJS wiki 上阅读它。而且Kris也给了talk on the topic back in 2010