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

What is preventing Safari and Firefox from properly handling audio data from MediaElementSource?

It appears that neither Safari nor Firefox can process audio data from a MediaElementSource with the Web Audio API. var audioContext, audioProcess, audioSource, response = document.createElement('h3'), display = document.createElement( ...

During bundling, utilize an npm script to copy the package.json file to the dist directory

Currently, I am facing a challenge while trying to enhance my npm bundle script. Although the initial part is functioning smoothly, I am encountering difficulties in including three additional files along with the bundle. At present, my script looks like ...

DOM not rendering Angular function output successfully

I recently delved into learning Angular and encountered a strange issue. Whenever I try to pull data using {{some.data.goes.here}} in the HTML, the result does not show up in the DOM. (function() { var app = angular.module('app', []); app. ...

typescript - instantiate an object using values stored in an array

Assume we have a model defined as follows. export interface Basicdata { materialnumber: number; type: string; materialclass: string; } We also have an array containing values that correspond directly to the Basicdata model in order, like this: ...

Tips for calculating the total of each row and column in a table with jQuery

<table id="repair-invoice"> <tr> <th>Item</th> <th>Parts</th> <th>Labor</th> <th>Total</th> </tr> <tr> <td>Oil Change</td&g ...

Tips for effectively utilizing Vuelidate to display errors selectively after the user has completed input:

I have implemented a form using Bootstrap-Vue with some Vuelidation code applied to it. <b-form @submit.prevent="onSubmit"> <input type="hidden" name="_token" :value="csrf" /> <transition-group name="fade"> <b-form ...

"Upload a video file and use JavaScript to extract and save the first frame as an image

I have a webpage where users can upload a video file, and the page will generate a thumbnail based on a timestamp provided by the user. Currently, I am focusing on generating the thumbnail from the FIRST frame of the video. Here is an example of my progr ...

Is it possible for any scripting language to interpret AJAX/JavaScript on a Linux platform?

Is it possible to extract data from web pages that utilize AJAX using Ruby and Mechanize on a Linux server without a monitor attached (such as Linode.com)? Perhaps a solution like would work, but I'm not sure if it's compatible with Linode. ...

What is the best way to know which API will return the result the fastest?

If we were to make 2 API calls, each taking around 6ms to return JSON data, what would be the sequence in which they provide the resulting data? The official JavaScript documentation mentions using Promise.all to manage multiple API calls. ...

The most efficient method for distributing code between TypeScript, nodejs, and JavaScript

I am looking to create a mono repository that includes the following elements: shared: a collection of TypeScript classes that are universally applicable WebClient: a react web application in JavaScript (which requires utilizing code from the shared folde ...

Establishing the state in a separate React component

I've tried various solutions found in other posts, but I still can't seem to resolve this issue. My main goal is to update the state of one component from another component. Below is a simplified version of my code: function updateOtherState(n ...

During the rendering process, the property "instance" was attempted to be accessed but is not defined

I am having trouble creating a Contact Us page using v-model. My code keeps throwing these errors: Property "inputted_name" was accessed during render but is not defined on instance Property "inputted_email" was accessed during render but is not defined o ...

CSS translation animation fails to execute successfully if the parent element is visible

Inquiries similar to this and this have been explored, but do not provide a solution for this particular scenario. The objective is to smoothly slide a menu onto the screen using CSS translation when its parent is displayed. However, the current issue is ...

Utilize ES6 syntax to bring in a package as an extension of another package

To expand map projections in D3, it is recommended to import the necessary packages like so: const d3 = require("d3") require("d3-geo-projection")(d3) This allows you to access methods such as d3-geo-projection's geoAiry method fr ...

Experience a seamless front/back DIV transition with a mouseover effect similar to the ones on USAT

Recently, I was tasked with creating a mouseover transition effect for a div similar to the one used on USAToday's website. The structure of the boxes on the site includes: <div class="asset"> <div class="front">'image and some t ...

Creating a repository of essential functions in AngularJSDiscover the steps to set up a

I am looking to create a set of reusable functions in AngularJS for CRUD operations that can be used across multiple entities in my project. I have already set up a factory using $resource for server communication, which looks like this: Model File: var ...

When attempting to decode a base64 image or pdf in PHP, the process fails if the file size exceeds 500kb

Currently, I am utilizing AJAX to upload files (either image or PDF). The process involves converting the file to base64, then sending the data via AJAX. On the server side (PHP), the data is processed to transform it into an image or a PDF. While my ser ...

What are some ways to create a div section within a Google Map interface?

Is there a way to create a div area within the Google map iframe? Some of my code is already prepared here (). The image in this link () illustrates exactly what I'm trying to achieve. ...

Having trouble deciding between Real AJAX and ASP.NET AJAX?

For over a year now, I have been utilizing ASP.NET in my work. The use of update panels allows me to update the page asynchronously without triggering a postback. I always assumed this functionality was Ajax-related. However, I recently learned that ASP.N ...

Maintain scrolling at the bottom with React.js

Is there a way to make a div element increase in height through an animation without extending beyond the viewable area, causing the window to automatically scroll down as the div expands? I am looking for a solution that will keep the scroll position lock ...