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

151
Visualizações
Why is async request with await not waiting for the response data?

im not sure why await is not working for me, can someone help me out? I followed some guides and copied it exactly the same but still won't work. I need CardsID array to be filled before calling console.log(CardsID.length)

code:

  "[LL_REPTAG_URLPREFIXFULL /]/api/v2/businessworkspaces?where_workspace_type_id=54";

async function postData() {
  let response = await fetch(url, {
    method: "GET", // *GET, POST, PUT, DELETE, etc.

    headers: {
      "Content-Type": "application/json",
      OTCSTicket: "[LL_REPTAG_OTCSTICKET /]",
    },

    //body: JSON.stringify(data) // body data type must match "Content-Type" header
  });

  return await response.json();
}

//(async function(){

postData().then(function (data) {
  // Log the data to the console
  // You would do something with both sets of data here
  //console.log(data);

  data.results.forEach((element) => {
    CardsID.push(element.data.properties.id);
    console.log("added");
  });
});
//})();

console.log(CardsID.length);
console.log(CardsID);```

result (console):

0
[]
[]
[]
24 added


about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You are calling the console.logs immediately after the postData() call, which is async (well, promise) and therefore won't wait for the execution to finish. Either you need to place the console.logs inside the then handler, like this:

postData().then(function (data) {
  data.results.forEach((element) => {
    CardsID.push(element.data.properties.id);
    console.log("added");
  });

  console.log(CardsID.length);
  console.log(CardsID);
});

Or (for the sake of consistency), you could make it all async/await, eg.:

async function postData() {
  const response = await fetch(url, {
    method: "GET", // *GET, POST, PUT, DELETE, etc.
    headers: {
      "Content-Type": "application/json",
      OTCSTicket: "[LL_REPTAG_OTCSTICKET /]",
    },
  });
  return await response.json();
}

async function run() {
  const data = await postData();

  const CardsID = [];
  for (const element of data.results) {
    CardID.push(element.data.properties.id);
    console.log("added");
  }

  console.log(CardsID.length);
  console.log(CardsID);
}

run();
about 4 years ago · Juan Pablo Isaza Relatório

0

The problem is that code in the postData().then block is executed asynchronously, after the promise get resolved. The console.log(CardsID.length) statement will run before the then block get executed.

To fix that, you can run the console.log statement in the promise callback.

postData().then(function (data) {

  data.results.forEach((element) => {
    CardsID.push(element.data.properties.id);
    console.log("added");
  });

  // move the console.log statement here
  console.log(CardsID.length);
  console.log(CardsID);
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Just remember that your code below the .then block will run before it resolves because Javascript waits to resolve but continues through its synchronous run to execute the code below the any asynchronous code.

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