What could be causing the async request with await to not properly wait for the response data?

I'm having trouble with the await function in my code, can anyone provide assistance? I've followed tutorials and copied the code exactly as shown but it still doesn't work. The CardsID array needs to be filled before I call console.log(CardsID.length)

Here is the 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);

Answer ā„–1

Immediately calling the console.logs after the postData() function will not wait for the asynchronous (promise) execution to finish. To address this, you can either place the console.logs inside the then handler, as shown below:

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

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

Alternatively, for consistency, you could refactor it using async/await like this:

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

Answer ā„–2

An issue arises when the code within the postData().then block is run asynchronously, after the promise has been resolved. This means that the console.log(CardsID.length) statement will be executed before the then block runs.

To resolve this issue, it is recommended to place the console.log statement inside the promise's callback function.

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

Answer ā„–3

It's important to keep in mind that the code after the .then block will be executed before it resolves since Javascript waits for resolution but still proceeds with its synchronous run to execute any code following asynchronous tasks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display Rails view using JavaScript when clicked

I have a task to create a view where users can click on different buttons and see different content displayed based on the button they choose. I attempted to achieve this using JavaScript, but unfortunately, I couldn't get it to work as intended. Init ...

What are some ways to utilize an empty array that has been declared in React's initial state?

I am currently in the process of developing an application that displays a collection of various lists. However, I have encountered a roadblock when attempting to access an empty array that I initialized when setting up the initial state. Here is the state ...

Default parameter in Node.js is set when the callback function is the last parameter

Here's a simplified version of the function I'm working with: doSmthg (name, age, callback) { callback(name, age); } I want to set a default value for age if it's not provided. In ES6, I could do doSmthg(name, callback, age=42) {...}, b ...

File appears to be empty after passing through ajax request

I have encountered an issue with my ajax submit function. When I submit the function, worklogdetailsidschedule and shift_schedule are successfully inserted into the database. However, the filename_schedule, which is a file, appears empty in the database. ...

When viewing my project on GitHub pages, the images within the card are not appearing

After running my project page link at https://nayaksofia.github.io/RestaurantReviewTest1/, I've noticed that the images inside the card are not displaying. However, when I run the same project on my local server localhost:8000, the images appear just ...

I could use some help navigating payment gateways

I'm new to payment gateways and would appreciate any recommendations or advice. ...

Transforming ExtNet DirectMethod from C# to VB.NET

Can you help me convert this code to VB.NET? [DirectMethodProxyID(IDMode = DirectMethodProxyIDMode.Alias, Alias = "UC")] public partial class AliasID : System.Web.UI.UserControl { [DirectMethod] public void HelloUserControl() { X.Msg ...

What steps should I take to ensure axios is returning the appropriate buffer type?

Upon initially posting this question, I was completely lost on where to even begin or how to appropriately title it. With the assistance of multiple comments, I enhanced the data provided and finally settled on the current question title - a big thank you ...

The declaration file for the module 'bootstrap/dist/js/bootstrap' could not be located

Currently, I am developing a Next.js application and have integrated Bootstrap for styling. However, I am encountering an error when trying to import the bootstrap.bundle.js file. I am facing the following error message: Could not find a declaration file f ...

The attribute of the Angular div tag that lacks an equal sign

Apologies if this question has been asked before. I've noticed in some people's code that they use the following syntax: <div ui-grid="myUIGrid" ui-grid-selection ui-grid-resize-columns class="grid" /> Can someone explain what ui-grid-sel ...

Tips on sending filter parameters from AngularJS to Spring RestController using @MatrixVariable

Iā€™m struggling to figure out how to use $http.get in AngularJS to pass filter parameters. The URL is: http://localhost:8080/template/users/query;username=abcd;firstName=ding... The RestController looks like this: @RequestMapping(value={"/users/{query ...

Is it possible to increment an integer value in jQuery after obtaining the sum result?

Actually, I'm trying to extract the integer value from my input field. For example, if I enter the value 4+5, I want to display the result as 9 in a separate div. However, instead of getting the expected result, I am receiving [object Object]. I&apo ...

Local server displaying 'Undefined' instead of the unique identifier

My goal is to create a script that will fetch a unique ID from a database when clicked. Despite searching various forums for a solution, I haven't been successful in finding one. <?php $table = mysqli_query($conn ,'SELECT * FROM co ...

Vue paginated select with dynamic data loading

My API has a endpoint that provides a list of countries. The endpoint accepts the following query parameters: searchQuery // optional search string startFrom // index to start from count // number of options to return For example, a request with searchQu ...

Implement rotation in Three.js that mirrors the functionality of Blender

Is there a way to permanently change the default rotation of a mesh in three.js after it has been loaded? For example, if I load a mesh with a rotation of 0,0,0, can I then rotate it 90 degrees on the X axis and set this new rotation as 0,0,0? It's i ...

Tips for preserving login status even after the browser is shut down with the help of JavaScript

I need help with maintaining a user session in my chat application even when the browser is closed. After users log in for the first time, I want their credentials to be remembered by the browser (I'm currently using local storage). How can I ensure ...

animations are not triggering when using ng-click inside ng-repeat, is there a reason why the event is not firing?

Check out the code in jsFiddler here After reviewing the code, it's clear that when the add button is clicked, a new item is pushed to the $scope.p. Each item in the ng-repeat loop has an event-binding and everything functions correctly. However, onc ...

I'm having trouble understanding how to utilize startAt and endAt in Firebase version 9

Trying to implement geo querying in my firestore db with the new version of firebase has been challenging. The code examples provided in the documentation reference an older version, making it difficult for me to understand how to use ".startAt" and ".endA ...

Combining JSON parameter and multipart/form-data file in a single request using Vue.js

Is there a way to send both JSON parameters and multipart/form-data files in a single request using Vue, similar to how Postman does it? I've been looking into how to submit "multipart/form-data" from VueJs. What I need is to include an image file in ...

Performing Vue CLI Global Upgrade

Struggling to create a new Vue.js project using the Vue CLI service, I encountered an error. With @vue/cli-service 3.0.0-beta.7 installed (confirmed by running vue -V), attempting to start a new project triggered the following error: ...