Search code examples
javascriptjqueryjquery-uiasynchronousdata-synchronization

How to retrieve data from multiple promise objects resolved through $.when in jQuery?


Suppose we have only one promise object like below.

var myPromise = $.get(url1);
myPromise.done(function(data){
    console.log(data);
});

We are able to access the data from the promise object. Now suppose, we have multiple promise objects resolved via $.when

var multiplePromises = $.when($.get(url1),$.get(url2),$.get(url3));
multiplePromises.done(function(){

});

The above requirement has to be satisfied, that is, only if all the get requests completes, the done part should get executed. But how do I individually get the data response from each get to work with them in the $.when.done() method?


Solution

  • You get them as arguments.

    function get(what) {
      return $.when(what)
    }
    
    $.when(get(1), get(2), get(3)).done(function(first, second, third) {
      console.log(first, second, third)
    })
    <script src="https://unpkg.com/jquery@3.2.1/dist/jquery.js"></script>