Chaining ajax requests with jQuery's deferred

后端 未结 7 2367
天涯浪人
天涯浪人 2021-02-19 19:46

I have a web app which must call the server multiple times. So far, I had a long nested callback chain; but I would like to use jQuery\'s when,then etc

7条回答
  •  独厮守ぢ
    2021-02-19 20:11

    As an update:

    With modern jquery (1.8+) you don't need the preliminary when because get returns a Deferred Promise.

    Also, pipe is deprecated. Use then instead. Just be sure to return the result of the new get which becomes the Promise attached to by subsequent then/*done*/fail calls.

    So:

    $.get('pages/run-tool.html')
    .then (function (args) { // this will run if the above .get succeeds
        // This works fine
        alert(args);
        $('#content').replaceWith (args);
        $('#progress-bar').progressbar ({value: 0});
    })
    .then (function() { // this will run after the above then-handler (assuming it ran)
        return $.get('pages/test.html'); // the return value creates a new Deferred object
    })
    .done (function(args) { // this will run after the second .get succeeds (assuming it ran)
        alert (args); 
    });
    

提交回复
热议问题