I suspect this question has been asked a million times, but it has been hard to find the right answer, and it is not obvious how to "force" the code to wait. I've seen answers that say javascript sync and async work like calling a friend for an answer, hanging up and doing something else, waiting for the friend to call back. But what happens and how do you force the code to wait for that "callback" when you have run out of other tasks but need the answer now?
I have 2 data elements being returned from a metadata call. The data for both elements show in the metadata element but after the assignment, they are blank. But, they both show when appended to the div.
Here is my code:
// The fetch call is asynchronous, so define a function that include the await instruction
async function fetchJson(API_url) {
const response = await fetch(API_url,{
method: "GET",
headers: myHeaders
});
const json = await response.json();
return json;
}
// basic metadata for a product
const fetchMetadata = (productApiLink) => fetchJson(`${productApiLink}?includeExtendedMetadata=false&includeToc=false`)
// create the paragraph elements from metadata
let psubtitle = document.createElement('p');
let pdesc = document.createElement('p');
let ptype = document.createElement('p');
// fetch the metadata for the current report
fetchMetadata(reports.products[i].apiLink).then(metadata => {
psubtitle.textContent = metadata.subtitle;
ptype.textContent = metadata.type;
console.log(ptype.textContent);
// take first 20 words of description, stripping out any html tags
pdesc.textContent = metadata.description.replace(/(<([^>]+)>)/gi, "").split(/\s+/).slice(0,20).join(" ") + "...";
console.log(metadata);
})
// both elements are blank here
console.log(ptype.textContent);
console.log(pdesc.textContent);
// putting it all together
// both show in the div!
div.appendChild(ptitle);
div.appendChild(psubtitle);
div.appendChild(ptype);
main.appendChild(div);
}
Thanks for helping me to understand. It has been a struggle reading and trying so many of these answers that just don't work for me.