简体   繁体   中英

Trying to use deferred objects and $.when to make multiple AJAX calls

So, based off of this tutorial on Medium ( https://medium.com/coding-design/writing-better-ajax-8ee4a7fb95f#.d7ymg99mp ), I am trying to use deferred arrays, ajax requests and jQuery.when method to make multiple ajax requests and obtain the result from each one of them.

Here is the code for what I am doing

function updateAllGoingButtons(){
    var dataToPass = {};
    var deferreds = [];

    $('.btn-group').find('button').each(function(){
       console.log($(this).attr('id'));
       dataToPass.button = $(this).attr('id');
       var ajax = $.ajax({
          url: '/update-buttons',
          method: 'post',
          data: dataToPass,
          dataType:'json'
       });

       deferreds.push(ajax);

       $.when.apply($, deferreds).then(function(){

       });
    });
}

My confusion arises as to how to use this $.when function and where I can access the data returned to the ajax call.

I tried inserting a simple success option, but that didn't enter its callback function. How do I do this?

You're just calling when too soon. Do it outside the each loop, after you've started all your ajax calls and gotten their promises in the array:

function updateAllGoingButtons(){
    var dataToPass = {};
    var deferreds = [];

    $('.btn-group').find('button').each(function(){
       console.log($(this).attr('id'));
       dataToPass.button = $(this).attr('id');
       var ajax = $.ajax({
          url: '/update-buttons',
          method: 'post',
          data: dataToPass,
          dataType:'json'
       });

       deferreds.push(ajax);

    });

    $.when.apply($, deferreds).then(function(){     // <=== Moved this
                                                    // <===
    });                                             // <===
}

The results of those ajax calls will be provided to your then function as a series of discrete arguments. Each argument will be an array with three entries, corresponding to the three arguments normally passed to success functions. Since you're dealing with an array, you'll probably want to access them via the arguments pseudo-array. It's also always a good idea to have a rejection handler (the second argument to then , or alternately use catch with recent versions of jQuery):

$.when.apply($, deferreds).then(
    function() {
        var n;
        for (n = 0; n < arguments.length; ++n) {
             console.log("Result " + n, arguments[n][0]);
        }
    },
    function() {
        // At least one request failed
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM