What is the way to execute a function *once* all my ajax call functions have finished?

I am utilizing jQuery to execute some ajax requests:

var information = {};

function process_information(item){
    information[item.id] = item;
}

function perform(){
    var calls = [];

    for(var i = 0; i < 10; i++){
        var call = $.get(URL, function(data){
             process_information(data);
        });
        calls.push(call);
    }

    $.when(calls).done(function(){
        console.log(information);
    });
}

In my implementation, I am using $.when. However, instead of receiving the anticipated data, I end up with an empty object {}. When examining this issue in Chrome, it appears that the log line is executed before any of the process_information calls. This indicates that the order of the callbacks may be mixed up. Is there a way I can ensure that the console.log(information) line is only triggered after all of my get callbacks have completed?

Answer №1

It would be beneficial for you to familiarize yourself with deferred objects by reading more about them: http://api.jquery.com/category/deferred-object/

You are making the right choice in using $.when, but keep in mind that it accepts arguments of deferred objects. Therefore, you will need something similar to $.when(calls[0], calls[1], ...). Although this may seem inconvenient, fortunately, you can use the javascript function .apply and come up with a solution like this:

$.when.apply(null, calls).done(function() {
    console.log(stuff);
}

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

Exploring the proper syntax of the reduce() method in JavaScript

Here are two codes that can be executed from any browser. Code1: let prices = [1, 2, 3, 4, 5]; let result = prices.reduce( (x,y)=>{x+y} ); // Reduces data from x to y. console.log(result); Code2: let prices = [1, 2, 3, 4, 5]; let result = prices.red ...

What are the practical applications and distinctions between single-page and multipage apps in AngularJS?

I've been exploring the differences between single page apps and multi page apps, and I believe I have a good grasp on their distinctions. Unlike multi page apps, a single page app begins by loading a single HTML page and does not fully refresh or ove ...

What could be causing this TypeScript class to not perform as anticipated?

My goal with this code snippet is to achieve the following: Retrieve a template using $.get(...), Attach an event listener to the input element within the template I am using webpack to transpile the code without encountering any issues. The actual cod ...

Iterating through a dataset in JavaScript

Trying to find specific information on this particular problem has proven challenging, so I figured I would seek assistance here instead. I have a desire to create an arc between an origin and destination based on given longitude and latitude coordinates. ...

MongoDB error codes and their associated HTTP status codes are important for developers to understand

When a new user attempts to sign up with an existing user account, MongoDb triggers a 11000 error code In Express, handling this scenario can be done as follows: async function signup(req, res, next){ try{ // perform some actions }catch(err){ i ...

Retrieve the value from an input field when the value is returned from JavaScript

Scenario: I'm currently working on creating a QR reader to retrieve a specific value. You can check out the progress here: What's functioning: scanning. When I scan a QR code, a value is displayed in the text box. Here's the code snippet b ...

Keep moving forward in Sailsjs even after sending back a response with res.json();

It will keep running even if the condition is met and the code inside return res.json() gets executed. _.each(rooms, function(room){ if(room.users.length == users.length) { return res.json(room); // <-- returns but execution continues } ...

Rest parameter ...args is not supported by Heroku platform

When interacting with Heroku, an error message SyntaxError: Unexpected token ... appears. What modifications should be made to this function for compatibility with Heroku? authenticate(...args) { var authRequest = {}; authRequest[ ...

What is the best way to connect the elements in two separate arrays?

I have a scenario with two arrays and a variable: var Names = ['jack', 'peter', 'jack', 'john']; var Ids = ['1' , '2' , '3' , '4' ]; Also, I have this search varia ...

Getting rid of a cookie from the header in Reactjs

Currently, I'm developing an application with Reactjs and utilizing the Next.js framework. To manage user authentication, I've implemented cookies. However, I am facing a challenge when it comes to logging out users and removing the cookie. Could ...

display different vue component based on screen size

I am in search of a method to implement responsive components in Vue.js (Nuxt). I have developed this mix-in but encountering an error: export const mediaQuery = { data() { return { breakpoints: { sm: 576, md: 768, lg: ...

passing a javascript variable to html

I am facing an issue with two files, filter.html and filter.js. The file filter.html contains a div with the id "test", while the file filter.js has a variable named "finishedHTML." My objective is to inject the content of "finishedHTML" into the test div ...

When the page loads, a JavaScript function is triggered

My switchDiv function in Javascript is being unexpectedly called when the page loads. It goes through each case in the switch statement, except for the default case. Does anyone know how to solve this issue? $(document).ready(function() { $("#be-button" ...

Do not attempt to log after tests have finished. Could it be that you overlooked waiting for an asynchronous task in your test?

Currently, I am utilizing jest in conjunction with the Vue framework to create unit tests. My test example is successfully passing, however, I am encountering an issue with logging the request. How can I resolve this error? Is there a mistake in my usage o ...

Utilize the Webstorm debugger in conjunction with node.js for seamless debugging

Several weeks ago, I attempted to get the webstorm debugger up and running, but unfortunately, it didn't work. Now, I'm giving it another shot, but I'm faced with the same outcome. I am following the instructions outlined here: http://www.j ...

Measuring the height of a div element using Vuejs

Let me explain my current situation: I am trying to determine the height of a DIV component in order to dynamically inform its child component about its size. I have been working on implementing manual loading mode, but I have encountered an issue where t ...

What steps should I take to address a situation in which a Protractor test becomes stuck indefinitely?

I've encountered an issue with a test case that was previously running successfully but is now getting stuck indefinitely during execution. This problem occurs each time the test attempts to click on a specific element, causing the test to hang withou ...

Tips for designing a search bar using Angular

search : ____________ I am interested in designing a search bar functionality that automatically triggers when the user inputs 8 or more characters. The input text will be stored in a variable, the search bar will be reset, and the backend API will be che ...

What is the process of assigning data, in JSON format, from an HTML form to a variable?

I have the coding below in my abc.html file, which converts form data to JSON format: <body> <form enctype='application/json' method="POST" name="myForm"> <p><label>Company:</label> <input name=& ...

Issues with receiving data on $.ajax POST request

If you'd like to check out my website Please use the following login details (case sensitive): Username: stack Password: stack Click on the tab labeled "yourhours." The main goal is to send all input box data to a database. At the moment, I am fo ...