0

I am trying to fetch data from an API and after that set data in web page. setting data should be done before rendering the page.

HTML code:

<div id="info">
    <h1 id="p_name"></h1>
    <h2>
       <a href="" id="p_spec"></a>
    </h2>
    <h3 id="p_numberp"></h3>
    <img id="p_image">
</div>

Javascript code is :

//readed data from API 
var page_data = {};

window.addEventListener('DOMContentLoaded', async function(){
    var parameters = location.search.substring(1).split("?");
    await fetchdata(parameters[0], function(){
        setdata();
    });
});

async function fetchdata(id, callback) {
    url = "https://my_url" + id;
    fetch(url)
    .then((resp) => resp.json()) // Transform the data into json
    .then((data) => (page_data = data));
  callback();
}
function setdata() {
    document.getElementById("p_name").innerHTML = page_data.name;
    document.getElementById("p_spec").innerHTML = page_data.spec;
    document.getElementById("p_image").src = page_data.avatar;
}

I tried this but it does not work (when i opened the web page, all items are undefined). thanks.

  • 2
    Does this answer your question? [How and when to use ‘async’ and ‘await’](https://stackoverflow.com/questions/14455293/how-and-when-to-use-async-and-await) – Randy Casburn Dec 29 '20 at 16:22
  • Here's your code, fixed: https://pastebin.com/UPdGPHWY –  Dec 29 '20 at 16:33

1 Answers1

1

You have two options here:

The callback call must be within the then call

async function fetchdata(id, callback) {
    url = "https://my_url" + id;
    fetch(url)
    .then((resp) => {
      page_data = resp.json();
      callback();
    })
}

Or you have to use the await keyword

async function fetchdata(id, callback) {
    url = "https://my_url" + id;
    // when using async calls we use await before calling a promise
    await fetch(url).then((resp) => page_data = resp.json())   
    callback();
}

Notice that, when we're using fetch, we should check if the response has "OK".
Something like this:

.then((resp) => {
  if (!resp.ok) return; // or do something else
  page_data = resp.json();
  callback();
})

Read more about it on the fetch doc

Felipe Malara
  • 1,796
  • 1
  • 7
  • 13