Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda