Run code once all ajax requests have been completed

Here's the code snippet I'm working with:

function updateCharts() {
    for (var i = 0; i < charts.length; i++) {
        updateChart(charts[i]);
    }

    sortQueues();
}

function updateChart(chart) {
    $.ajax({
        type: "POST",
        async: true,
        data: '{id: ' + chart.Id + '}',
        url: "foo/getData",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var parsedResponse = JSON.parse(response.d);
            insertChartData(chart, parsedResponse);
        },
        failure: function (response) {
            console.Log(response);
        }
    });
}

I'm facing an issue where the sortQueues() function is being run before all charts are updated due to ajax calls. As a result, the charts in the HTML aren't sorted as expected. Can anyone suggest a way to ensure that sortQueues() is only executed after all instances of insertChartData have completed, without resorting to synchronous calls?

Answer №1

$.ajax provides a promise, allowing you to capture and utilize them with the help of Promise.all.

To begin, retrieve the promise:

function updateChart(chart) {
    return $.ajax({

Next, replace your loop with map to gather all promises within an array.

var promises = charts.map(updateChart);

Finally, leverage the promise:

Promise.all(promises).then(array_of_results => {
    // All ajax requests have been completed at this point
});

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

Is there a way to pass a variable from a Django view to an HTML page using Ajax when the user presses a key

I am developing an application that delivers real-time data to users in HTML, and I aim to dynamically update the paragraph tag every time a user releases a key. Here is a snippet of my HTML: <form method="POST"> {% csrf_token %} <p id="amount_w ...

Adding elements to a two-dimensional array using AngularJS

How can I assign the value of an input to tasks.name and automatically set status: false when adding a new item to the $scope.tasks array? HTML <input type="text" ng-model="typeTask"> <button ng-click="updateTasks()">Add task</button> ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

Dealt with and dismissed commitments in a personalized Jasmine Matcher

The Tale: A unique jasmine matcher has been crafted by us, with the ability to perform 2 key tasks: hover over a specified element verify the presence of a tooltip displaying the expected text Execution: toHaveTooltip: function() { return { ...

Can React JSX and non-JSX components be combined in a single project?

I'm currently faced with a question: If I have a parent component in JSX but need to include an HTML tag like <i class="fa fa-window-maximize" aria-hidden="true"></i>, which is not supported by React JSX (correct me if I'm wrong), can ...

Difficulty accessing class functions from the test application in Node.js NPM and Typescript

I created an NPM package to easily reuse a class. The package installs correctly and I can load the class, but unfortunately I am unable to access functions within the class. My project is built using TypeScript which compiles into a JavaScript class: For ...

Is there a way to verify the phone number input field on my registration form along with the country code using geolocation

I'm currently working on a registration form that includes an input field for telephone number. I'd like to implement a feature where, upon filling out the form, the telephone input field automatically displays the country code by default. Would ...

Setting the state of a nested array within an array of objects in React

this is the current state of my app this.state = { notifications: [{ from: { id: someid, name: somename }, message: [somemessage] }, {..}, {..}, ] } If a n ...

What is the best way to display only a specific container from a page within an IFRAME?

Taking the example into consideration: Imagine a scenario where you have a webpage containing numerous DIVs. Now, the goal is to render a single DIV and its child DIVs within an IFrame. Upon rendering the following code, you'll notice a black box ag ...

How can I update getServerSideProps using a change event in Next.js?

Currently, I am faced with the task of updating product data based on different categories. In order to achieve this, I have set up an index page along with two components called Products and Categories. Initially, I retrieve all products using the getServ ...

Handling asynchronous behavior in the context of conditional statements can be a challenging aspect of

Currently, this code section is passing undefined to if(customerWaiting >0). It's an async issue that I'm struggling to resolve. Despite my efforts and research on other threads, I can't seem to make this basic newbie question work. I&a ...

The plugin function cannot be executed unless inside the document.ready event

Utilizing jquery and JSF to construct the pages of my application includes binding functions after every ajax request, such as masks and form messages. However, I am encountering an issue where I cannot access the plugins outside of $(function(). (functio ...

GSAP also brings scale transformations to life through its animation capabilities

I have an SVG graphic and I'm looking to make four elements appear in place. I've been using GSAP, but the elements seem to be flying into place rather than scaling up. Here's the code snippet I've been using: gsap.fromTo( ...

Is it possible for me to generate values using PHP that can be easily read by JavaScript?

I'm currently building a website and I am facing some challenges when trying to incorporate JavaScript for real-time calculations. Here are my issues: Is there a more efficient way to avoid manually typing out the code for each level up to 90, lik ...

Concluding the use of angular-bootstrap-datetimepicker when selecting a date

I am currently utilizing the UI Bootstrap drop-down component to display the angular-bootstrap-datetimepicker calendar upon clicking. Although it works well for the most part, I have encountered an issue where the calendar block does not close when clicked ...

The jQuery fadeOut function modifies or erases the window hash

While troubleshooting my website, I discovered the following: /* SOME my-web.com/index/#hash HERE... */ me.slides.eq(me.curID).fadeOut(me.options.fade.interval, me.options.fade.easing, function(){ /* HERE HASH IS CLEARED: my-web.com/index/# * ...

The Enigmatic Essence of TypeScript

I recently conducted a test using the TypeScript code below. When I ran console.log(this.userList);, the output remained the same both times. Is there something incorrect in my code? import { Component } from '@angular/core'; @Component({ sel ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

Using PHP and jQuery to generate push notifications can result in issues with server performance

To simulate push notifications using PHP, I have implemented the following method: An AJAX call is made to a server-side script using jQuery. The script includes a for loop with a sleep function after each iteration to introduce delay. If a certain condi ...

Showing the json encoded array received from an ajax response

I have encountered this data result {"policy":[{"id":"1","policy_name":"Policy 1","description":"Testing","status":"Active","valid_until":"2022-05-18& ...