Home > Software engineering >  Why is async request with await not waiting for the response data?
Why is async request with await not waiting for the response data?

Time:10-23

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


CodePudding user response:

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();

CodePudding user response:

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);
});

CodePudding user response:

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.

  • Related