What is the best pattern for checking completion of jquery promises in JSON objects?

时间:2016-07-11 20:53:23

标签: jquery json promise getjson

I have a list of numbers and I want to create an array of JSON objects with created from querying the numbers from an api. For example, if the numbers are

numbers = [1, 4];

Then I want a JSON object created like such:

[{
  number: 1,
  data: $.getJSON('/api/numbers/1')
},
{
  number: 4,
  data: $.getJSON('/api/numbers/4')
}]

The simplest way I would think would be to map the list of numbers to a corresponding JSON object:

numbers_data = numbers.map(n => {number: n, data: $.getJSON('/api/numbers'+ n)})

However, once I have the numbers_data with the embedded $.getJSON promises, I'm not sure how to tell when all the api calls have completed. Is there a pattern that would let me tell when the variable numbers_data is fully resolved so that I can do something with it?

1 个答案:

答案 0 :(得分:0)

You can use $.when to basically "combine" the promises into one. You can then attach a .done() handler to the output of $.when and know once all your AJAX calls are done. You can then access all the returned JSON data and use it/build your object as needed.

Something like this:

var promises = [],
    numbers_data = numbers.map(number => {
        var data = $.getJSON('/api/numbers'+number);

        promises.push(data);
        return {number, data};
    });

// This will let you know once *all* promises are resolved.
$.when.apply($, promises).done(() => {
    // Each argument is an array with the following structure: [ data, statusText, jqXHR ]
    for(var i = 0, len = arguments.length; i < len; i++){
        numbers_data[i].data = arguments[i][0];
    }
});