javascriptjqueryasynchronousgetjson.when

Dynamically call getJSON inside $.when block


Is there some way to rewrite this in less lines of code, by making it dynamic instead of doing multiple similar calls with different indexes?

var input = getInput();
var URL = getEndpointURL();
var results = [];
        $.when(
            $.getJSON(URL+input[0], function (data,status) {
                results[0] = data;
            }),
            $.getJSON(URL+input[1], function (data,status) {
                results[1] = data;
            }),
            $.getJSON(URL+input[2], function (data,status) {
                results[2] = data;
            }),
            $.getJSON(URL+input[3], function (data,status) {
                results[3] = data;
            }),
            $.getJSON(URL+input[4], function (data,status) {
                results[4] = data;
            }),
        ).then(function() {
            processResults(results);
        });

Solution

  • Assuming input is an array you can map() the array to request promises and use Promise.all() on that array.

    const URL = 'https://jsonplaceholder.typicode.com/todos/',
          input = [3, 5, 6];
      
    const requestPromises = input.map(function(inp) {
        return $.getJSON(URL + inp);
    });
    
    Promise.all(requestPromises).then(processResults)
    
    function processResults(data) {
      console.log(data)
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>