Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

212
Vistas
Render API/Json data using Async Await in Html using javascript

I want to render JSON data in HTML in div with id content in paragraph tags in this format -

ID:XYZ

Username : ABC

Age : Kd

How can I do it ?? I am new in async-await, can someone help me ??

./user.json file

[
{
    "id":1002,
    "username":"dcode",
    "age":30

},

{

"id":1140,
"username":"otheruser",
"age":41
}


]
//My async await 
async function loadUsers()
{
    const response = await fetch("./user.json");
    return response.json();

}

document .addEventListener('DOMContentLoaded',async()=>{
try{
    users = await loadUsers();

}
catch (e)
{
    console.log("ERROR");
    console.log(e);

}

console.log(users);



})
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

After fetching the data you can create paragraph elements, add user data to the innerText of the paragraph element and then append it to the div container having id content

async function loadUsers() {
  const response = await fetch("./user.json");
  return response.json();
}

document.addEventListener("DOMContentLoaded", async () => {
  try {
    const users = await loadUsers();
    const divContainer = document.getElementById('content');
    users.forEach(user => {
        const paragraphElem = document.createElement('p');
        paragraphElem.innerText = `ID: ${user.id} \n Username: ${user.username} \n Age: ${user.age}`;
        divContainer.appendChild(paragraphElem);
    });
  } catch (e) {
    console.log('ERROR');
    console.log(e);
  }
});
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="content"></div>
  <script src="script.js"></script>
</body>
</html>
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can't control when your script is going to execute, At times it's possible that DOMContentLoaded was already fired by the time you get a chance to listen for the event.

To take that into consideration, your code needs to check if DOMContentLoaded was already fired and, if so, proceed to execute right away whatever it is that needed to wait for DOMContentLoaded:

Refer this answer

A working example of what you want to achieve.

//My async await
async function loadUsers() {
  let response = await fetch("https://api.sampleapis.com/wines/reds");
  return response.json();
}

let users;

async function runWhenPageIsFullyParsed() {
  console.log("on content load");
  try {
    users = await loadUsers();
  } catch (e) {
    console.log("ERROR");
    console.log(e);
  }

  console.log(users);
}

if (document.readyState === "complete") {
  runWhenPageIsFullyParsed();
} else {
  window.addEventListener("DOMContentLoaded", runWhenPageIsFullyParsed);
}

Note: I have used an external link here for example.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda