简体   繁体   中英

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.

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;
        });
    }
}

$.getJSON returns a Promise, which you can then await to halt execution and get the result:

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

To squeeze the whole bandwith out of your connection, you could run the requests in parallel and then show the divs all at once:

async function loadData() {
  const promises = [];
  for (let i = 0; i < 8; i++) {
    promises.push($.getJSON("http://theapi.com/data" + i));

  const result = await Promise.all(promises);

  for(const data of result) {
    const div = "<div>" + data + "</div>";
    browserElement.innerHTML += div;
  }
}

Read on

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM