jQuery Ajax Chaining

分享一個jQuery 的Ajax Chaining技巧

可以有效避免Call back hell的醜陋程式碼


$.ajax({...}).then(function(){
    return $.ajax({...});
}).then(function(){
    return $.ajax({...});
}).then(function(){
    return $.ajax({...});
}).then(function(){
    return $.ajax({...});
});

分享另一個實用的jQuery api:

jQuery.getJSON()

該api其實就把ajax再包過一層:


$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});

 

 

以上的code就可以改為

$.getJSON(url, data)
.then(function(result){
   $.getJSON( url, data)
})
.then(function(result){
   $.getJSON( url, data)
})
.then(function(result){
 $.getJSON( url, data)
})

 

另外參考Promise的做法:


var promise = $.getJSON(url);

promise.done(function(data) {
 ...do something;
});

promise.fail(function() {
 ...do something;
);
});

 

至於想要用done(…),fail(…)做chaining是行不通的,

.then will create a new deferred (補充:看api介紹應該是Promise而非 deferred) and add that to the chain. The next thing you do on the chain, such as .done or .then, will only have access to what was returned from the previous .then. – Kevin B Jun 20 ’13 at 15:08

假設寫成:

//WORNG CODE
$.getJSON(url, data)
.done(function(result){
   $.getJSON( url, data)
})
.done(function(result){
   $.getJSON( url, data)
})
.done(function(result){
 $.getJSON( url, data)
})

你所有的.done都會拿到第一個async的deferred object,所以同一時間會印出3個結果。

可以看一下

https://api.jquery.com/deferred.then/

https://api.jquery.com/deferred.done/

這兩個api的介紹以及return的值。

Ref:

main idea: http://stackoverflow.com/questions/17216438/chain-multiple-then-in-jquery-when

https://davidwalsh.name/write-javascript-promises

http://callbackhell.com/

Write Better JavaScript with Promises:https://davidwalsh.name/write-javascript-promises

Difference between .done() and .then():  http://stackoverflow.com/questions/17216438/chain-multiple-then-in-jquery-when#comment24941432_17216555

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s