Search code examples
javascriptjqueryajaxpromise.when

Proper way to run multiple similar ajax calls with same done function, differing in input data


So I am trying to a multiple ajax requests to the same place for almost the same json, but I'll be sending different data each time.

Here is what I have so far, I added each ajax request to an array and then am trying to run a $.when on the array, but nothing is happening. I swear I have seen this before and this is like how it is done. Just wondering what is the proper way to run multiple ajax calls like this. They don't depend on each other, but the resulting json is manipulated and use the same way for each request.

Here is my code:

var requests=[]
$('.element').not('.w').each(function(){
        requests.push($.ajax({url:'https://api.url.com', data:{'q':$(this).children('.supportingText').text(), 'token':''}, dataType:'jsonp', method:'GET'}));
    });
$.when(requests).done(function(response){
    //check if element in response object is something and then add to array and edit the .element that is currently on.
}

Solution

  • Unlike real promises, jQuery's promises are a little different. $.when doesn't take an array of promises in it's argument, it takes multiple arguments

    Using Function#apply you can use an array to "fill out' the arguments

    Similarly, the .done gets called with one argument per input argument

    Your code can be rewritten:

    $.when.apply($, requests).done(function(){
        var response = [].slice.call(arguments);
        // response is an array of responses
    })
    

    or ES2016+ spread operator (in case you think otherwise, the ... is actually part of the code)

    $.when(...requests).done(function(...response){
        // response is an array of responses
    })