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

2 thoughts on “jQuery Ajax Chaining

  1. I’m now not positive the place you are getting your information, however great topic. I must spend a while finding out much more or understanding more. Thank you for magnificent information I used to be in search of this information for my mission.

    Like

    1. Glad I can help.
      The references came from stack overflow, where I searched a solution for work.
      It’s only a snippet, but it inspired me about chaining technique.
      I found that chaining is common in many javascript api/frameworks.
      Till recently I start to familiar with event driven programming.

      Like

Leave a reply to Alex Cancel reply