ロイドの発言は私が知る限り正しいものですが、それがまさにあなたが探していた答えだとは思いません。これが私の試みです。
まず、据え置きのpromiseを使用する場合、戻り値として期待および提供する唯一の合理的なものは、promiseオブジェクトです(したがって、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:
});
あなたはdefferedスタイルの実装でそのようなことをしたいと思います:
/* 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)をいじって、CommonJSwikiでそれについて読んだことです。そして、クリスはまた 、2010年にこのトピックについて講演しました