As an example, suppose that i want to build a dynamic HTML pages showing the properties of all the planets and moons of the solar system, loading the data from an observatiry server API.
I do a GET request to get a json containing all the planets of the solar system.
I then need to loop each planet to write the HTML page, but i need to do a GET request to get another json object containing all the moons of a given planet.
So, my code looks like this:
async function GetPlanets(Star) {
const response = await fetch('https://observatory.app/api/planets?name=${Star}');
var data = await response.json();
showPlanets(data); // This function writes the innerhtml of a table,
}
async function GetMoons(Planet) {
const response = await fetch('https://observatory.app/api/moons?name=${Planet}');
var data = await response.json();
return showMoons(data); // This function writes the innerhtml of a table
}
function showPlanets(data) {
let tab =
`<thead><tr>
<th>name </th>
<th>mass </th>
<th>gravity </th>
<th>moons </th>
</tr></thead>
`;
// Loop to access all the planets
tab += `<tbody>`;
for (let r of data.all_planets) {
tab += `<tr>
<td rowspan=2> ${r.name }</td>
<td> ${r.mass }</td>
<td> ${(r.gravity).toFixed(2) }</td>
</tr>`;
// Now add the moons
tab += `<tr><td id="moons" colspan=3>`
tab += GetMoons(r.name); // GET the moons of this planet
tab += `</td></tr>`;
}
tab += `</tbody>`;
// Setting innerHTML as tab variable
document.getElementById("systemPlanets").innerHTML = tab;
}
function showMoons(data) {
let tab =
`<table><thead><tr>
<th>name </th>
<th>mass </th>
<th>gravity </th>
</tr></thead>
`;
// Loop to access all the moons
tab += `<tbody>`;
for (let r of data.all_moons) {
tab += `<tr>
<td> ${r.name }</td>
<td> ${r.mass }</td>
<td> ${(r.gravity).toFixed(2) }</td>
</tr>`;
}
tab += `</tbody></table>`;
return tab;
}
At the end of the <body> section there’s the call to getPLanets(Sol); and the page should then show the data.
Now, i see that all the request receives an answer, but my page did not get built. I see the planet table for a brief moment and then it just show “undefined”.
Searching for a solution I learned that async function cannot return a value, and also I think I’ve understood that the async functions should not be called in the way I do, but really i know nothing about promises and async/await so I’m struggling to get what should I do.
For what i’m understanding, I don’t want to have all the request in parallel, instead i just want to process each planet/moon one at time…
How can i do all the GET requests after the first one and write the data in the page?



