Async/Await moves on to the next function without waiting for the previous function to finish executing

I am developing a web application that requires querying my database multiple times. Each query depends on the data retrieved from the previous one, so I need to ensure each call completes before moving on to the next. I have attempted using async/await for this purpose, but it seems there may be an issue with my approach. Can someone provide guidance on the correct way to achieve this?

var firstCall = new XMLHttpRequest();
var firstCallData;
async function initiateFirstCall() {
  firstCall.open('GET', queryURL);
  firstCall.onload = function() {
    firstCallData = JSON.parse(firstCall.responseText);
  };
  firstCall.send();
};

async function displayData() {
  await initiateFirstCall();
  console.log(firstCallData);
}

displayData();

I have some experience in JavaScript, although I do not frequently write code in it and might not fully understand how async/await functions work. Any assistance or insights would be greatly appreciated!

Answer №1

The sendFirstCall method is not returning a meaningful Promise, so there isn't any need to use await. It may be worth considering using modern Promise functionality with tools like fetch or Axios instead of relying on the old XMLHttpRequest. You can wrap it in a Promise for better handling, like this:

function sendFirstCall() {
  return new Promise(function(resolve, reject) {
    firstCall.open('GET', queryURL);
    firstCall.onload = function() {
      firstCallData = JSON.parse(firstCall.responseText);
      resolve();
    };
    firstCall.send();
  });
}

I removed the async keyword from the function definition as it's unnecessary when manually returning a Promise that can still be awaited by consuming code.


Another approach would be resolving the Promise with the data itself:

function sendFirstCall() {
  return new Promise(function(resolve, reject) {
    firstCall.open('GET', queryURL);
    firstCall.onload = function() {
      resolve(JSON.parse(firstCall.responseText));
    };
    firstCall.send();
  });
}

Then, the consuming code can simply await the result:

firstCallData = await sendFirstCall();

This way, the operation remains free of side effects and just returns a value asynchronously for the consuming code to handle.


You could also utilize the reject callback within the Promise to manage errors if the XMLHttpRequest fails or encounters an error. Otherwise, the failure would go unnoticed, and the Promise would never be resolved or rejected.

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

Guide to tallying the occurrences of a specific key within an object array and attaching the count to each key's current value

Is there a way to determine the number of occurrences of the 'value' key within an object that is part of an array, and then add the count to each value if applicable? In this case, 'a' represents the original data var a = [ { id: ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Manipulating a global variable in VueJS

Currently, I am referring to Global data with VueJs 2 for my project, focusing on only one variable. In the code provided, I have included an @click event to update the variable. However, it throws an error stating "Uncaught ReferenceError: $myGlobalStuff ...

"Enhancing User Experience with jQuery: Implementing a Smooth Scroll Feature with Current

I could really use some guidance on this issue that's been causing me trouble. Take a look at this fiddle for reference: http://jsfiddle.net/NtUpw/ Currently, the code is functioning as expected. However, I'm facing an issue where when the curre ...

React component failing to update when props change

After loading correctly, my react component fails to re-render when props change. Despite the fact that render() is being called and the list array contains the correct data according to console.log(list), the page does not refresh. Adding a setState in co ...

Lambda function failing to execute Auth0 methods through the Auth0 node-auth0 SDK

I am working with a lambda function that triggers when a message is added to the SQS queue. Within the message, there is a userId that I want to connect to using the Auth0 node SDK. The code snippet for my GetUserDetails function below shows that it logs ...

What is the method to effectively conduct a testing procedure for JavaScript files that have been exported using

I have a JavaScript file called "sum.js" which contains a simple function: // sum.js function sum(a, b) { return a + b; } export default { sum }; Now I want to write a test for this file using Jest. Here is my "sum.test.js" file in the same folder: // ...

Sending state information through props in a Vuex environment

One of the challenges I am facing is how to make a reusable component that can display data from the store. My idea is to pass the name of the store module and property name through props, as shown below: <thingy module="module1" section=" ...

Can the server determine if a Parse user is currently logged in?

My current system allows users to log in or sign up client side, but I want to verify their login status from the server when they land on a page through a GET request. Is it feasible to do this? ...

Hovering over the child element, instead of the parent

I'm working on implementing a highlight feature for my website. The structure of the HTML looks something like this: <div> <!-- this is the main container --> <div> content ... </div><!-- a child element --> < ...

Issue encountered while utilizing combineReducers: "Error: The assetsReducer returned an undefined value during initialization."

Issue: The "assetsReducer" has returned an undefined value during initialization. When the state passed to the reducer is undefined, it must explicitly return the initial state, which cannot be undefined. If no value is set for this reducer, consider using ...

Generating a primary XML element encompassing multiple namespaces

I am currently working on integrating Restful services with Backbone.js framework. In this project, I need to send XML data and add multiple namespaces to it. Here is the snippet of my current JavaScript code: var mainNamespace = "xmlns='http://serv ...

Ways to confirm the actual openness of Express app's connection to MongoDB?

I'm currently developing an Angular 7 application that utilizes MongoDB, Node.js, and Express. One issue I encountered is that if I start my Express app (using the npm start command) before connecting to MongoDB (using the mongod command), the Express ...

Issue: The plugin 0 mentioned in the file "/my dir/node_modules/babel-preset-php/src/index.js" contains an invalid property called "default"

While attempting to convert a PHP script to JavaScript using babel-preset-php, I encountered the following error: Error: Plugin 0 specified in "/media/deep/5738c180-2397-451b-b0b5-df09b7ad951e1/deepx/Documents/TestingAll/node_modules/babel-preset-php/ ...

What is the best way to create a new row at a specific index in an ng-repeat loop?

My Goal: I am aiming to insert a new row of ul after every 2 elements in my ng-repeat loop. For example: <ul class="col-sm-2"> <li><p>Automobile & Motorcycle</p></li> ...

ajax-triggered forms

Is there a way to ensure that a form functions correctly when it is included in the HTML loaded via AJAX? I am utilizing jQuery for this task. Any suggestions or advice would be appreciated. ...

The double click functionality does not seem to be functioning within the Backbone View

I am trying to detect double click event within a Backbone view var HomePage = Backbone.View.extend({ initialize: function(){ this.render(); }, render: function(){ var template = _.template($('#app1').html()); ...

Encountering an error in AngularJS $http calls while trying to loop: TypeError - object is not functioning

Currently, I am in the process of automating the population of my app's database with Dummy Data to eliminate the manual task of adding users, friends, and more. To achieve this, I have implemented nested AngularJS $http requests that interact with my ...

changing button text in ajax upon successful completion

I am looking to update the button text upon successful completion. Specifically, I would like to change it to "accepted" after a successful response. <button type="button" onclick="saveData<?php echo $row1->id; ?>()">Accept</button> ...

There seems to be this strange and unexpected sharing of Animated.View and useRef between different child components

Currently, I am displaying a list of items in the following manner: {formattedJournal[meal].map((food, idx, arr) => { const isLast = idx === arr.length - 1; return ( <View key={idx}> ...