Search code examples
javascriptcssapiasync-awaitdom-manipulation

javascript: Update the DOM only when the result is ready


I have some api endpoint.

one returns all server details (https://dnscheck.io/api/serverDetails/) others are server specific endpoint. (https://dnscheck.io/api/query/?id=2&type=A&hostname=test.com) for each server_Id(which I got from serverDetails endpoint), I have to call each api endpoint.

what I have done is.

I loop over the results array (which I got from serverDetails endpoint)

and for each iteration of loop, I call each endpoint for getting the ip.

loop:

 for (const [index, item] of data.entries()) {
    const res = await fetch(
      `https://dnscheck.io/api/query/?id=${item.id}&type=${query.type}&hostname=${query.host}`
    );
    const result = await res.json();

    renderResult(result, item, index);
  }

render-function:

const renderResult = (result, data, index) => {

  const ip = document.querySelector(`.ip-address${index + 1}`);
  ip.innerHTML = result.answers[0].address;

};

In this way, results are displayed in the DOM in a sync way. (one after another)

But, what I want is, update the dom with the result, as soon as the result is ready.

what can I do?


Solution

  • Don't use await, as that blocks the for loop and orders the results. Use .then() instead.

    for (const [index, item] of data.entries()) {
      fetch(
          `https://dnscheck.io/api/query/?id=${item.id}&type=${query.type}&hostname=${query.host}`
        ).then(res => res.json())
        .then(result => renderResult(result, item, index));
    }