Search code examples
javascriptgetjson

Loading API requests in order (JavaScript)


The script I'm writing makes several API calls within a for loop. The problem is that some API calls take longer to load than others so the information is loaded on the page out of order.

For example, I'll make an API call for objects 1-8, but they'll load in the following order: 4, 3, 1, 2, 7, 5, 6, 8

The code is basically the following:

function loadData() {
    for (var i = 0; i < 8; i++) {
        $.getJSON("http://theapi.com/data" + i, function(data) {
            var div = "<div>" + data + "</div>";
            browserElement.innerHTML += div;
        });
    }
}

How can I force the JavaScript not to load the second API call until the first one is finished?

Edit: Using "promises" to chain the API calls results in the script waiting to display the data until ALL of it has been loaded. This is not a desirable result since, if there's enough data, the user may have to wait more than a few seconds to see anything.


Solution

  • Create all your divs in the loop and then populate with data once it is available

    function loadData() {
        for (var i = 0; i < 8; i++) {
            let div = document.createElement("div");
            browserElement.innerHTML += div;
    
            $.getJSON("http://theapi.com/data" + i, function(data) {
                div.innerHTML = data;
            });
        }
    }