Executing several Ajax requests at once can decrease the speed of the process

When I make simultaneous API calls using Ajax, the process seems to be slow as JavaScript waits for all API responses instead of fetching them asynchronously.

For instance, /api/test1 usually responds in 5 seconds and /api/test2 also responds in 5 seconds. However, when both are called simultaneously, it takes 10 seconds to complete.

To illustrate, the combined call takes 10 seconds:

$.get("/api/test1", function() {
    self.responseHandler1();
});
 $.get("/api/test2", function() {
    self.responseHandler2();
});

In order to speed up the process, I have been implementing the following approach:

$.get("/api/test1", function() { // 5 sec
    self.responseHandler1(); 
    $.get("/api/test2", function() { // 5 sec
        self.responseHandler2();
    });
});

If you have any suggestions or a better solution for handling multiple API calls more efficiently, please advise me.

Answer №1

Your code

$.get("/api/test1", function() {
    self.responseHandler1();
    $.get("/api/test2", function() {
        self.responseHandler2();
    });

does not fetch test2 until test1 has been acquired

This snippet of code

$.get("/api/test1", function() {
    self.responseHandler1();
});
$.get("/api/test2", function() {
    self.responseHandler2();

fetches the two requests simultaneously

and this block of code

$.when($.get("/api/test1"), $.get("/api/test2")).then(function(resp1, resp2) {
    self.responseHandler1();
    self.responseHandler2();
});

sends the requests in parallel, but executes both response handlers only after both requests are completed

as an experiment (related to the modified code in the question and the comment below)

var x = Date.now();
$.get("/api/test1", function() {
    self.responseHandler1();
});
console.log(x - Date.now());
$.get("/api/test2", function() {
    self.responseHandler2();
});
console.log(x - Date.now());

The values printed on console should be small numbers (likely less than 100) - if they are not, then your $.get is not running asynchronously - my understanding of jQuery might not be current, but there could be a way to make the default request synchronous, which might be affecting your code - alternatively, the issue could lie with the server, possibly struggling with concurrent requests, or the API operations on the server end may be causing a bottleneck - regardless, if those logged values are large, the problem likely stems from the server

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

How to update router query in Next JS without triggering a page change event

I am seeking a solution to modify a URL query for the current page in Next JS without causing the page change event to trigger. Specifically, I need to be able to remember the week that is being viewed in a calendar, much like how Google Calendar operates. ...

Combining Mongoose OR conditions with ObjectIDs

After querying my Team schema, I am receiving an array of ids which I have confirmed is correct. The issue seems to lie in the fact that both home_team and away_team are ObjectIDs for the Team Schema within my OR statement. Team.find({ 'conferenc ...

Easy Div Centering with jQuery Toggle for Internet Explorer 6

Press the button to center the div, press it again to align it to the left. This feature is compatible with all browsers except for IE6, which does not support margin: 0 auto;. How can I find a solution to this issue? The width of the div is not fixed and ...

Issues with submitting a Django form using AJAX

I am experiencing an issue with the URL when trying to create a "like button" using AJAX. Whenever I click on the button, I receive a 404 error with the following URL: 'add_like'%20%%7D. The server console responds with "POST /questions/get/1/%7B ...

Is there a way to use Javascript or JQuery to conceal all unchecked items in a RadioButtonList?

Currently, I am utilizing the Asp .net repeater to bind the selected value in the RadioButton list. Here is an example snippet: <asp:RadioButtonList ID="RadioButtonList1" runat="server" SelectedValue='<%# Eval("Numbers& ...

Issue with AngularJS ui-router failing to resolve a service call

I am facing an issue while trying to implement the resolve feature in my ui-router state provider. Here is how I have configured it: app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stat ...

Guide to changing a 10-digit number field to a string field in MongoDB

Looking to change the mobile field to a string in MongoDB. { "_id": "1373b7723", "firstname": "name1", "mobile":1000000099 }, { "_id": "137be30723", "firstname": "name2&qu ...

A guide on using jQuery-Tabledit and Laravel to efficiently update table rows

In Laravel, it is necessary to include the row ID in the request URL to update it, for example: http://localhost/contacts/16 The challenge arises when using jQuery-Tabledit, which requires a fixed URL during initialization on page load. Hence, the query ...

HighCharts.js - Customizing Label Colors Dynamically

Can the label color change along with gauge color changes? You can view my js fiddle here to see the current setup and the desired requirement: http://jsfiddle.net/e76o9otk/735/ dataLabels: { format: '<div style="margin-top: -15.5px; ...

What is the best way to incorporate variables into the useState hook in React?

I want to create multiple useState hooks based on the length of the userInputs array. The naming convention should be userInput0, userInput1, userInput2,...userInputN. However, using "const [userInput+index.toString(), setUserInput] = useState('' ...

Building a Node.js authentication system for secure logins

Just diving into node.js and trying to create a user login system, but encountering an error when registering a new user: MongoDB Connected (node:12592) UnhandledPromiseRejectionWarning: TypeError: user is not a constructor at User.findOne.then.user ...

A comparison between the Composition API and traditional Plain JavaScript syntax

I'm currently exploring the necessity of utilizing the 'new' Vue Composition API. For instance, take the following component extracted from their basic example: <template> <button @click="increment"> Count is: {{ ...

Struggling to align my image in the center while applying a hover effect using CSS

Hey there, I'm having an issue centering my image when I add instructions for it to tilt on mouseover. If I take out the 'tilt pic' div, the image centers just fine. Can anyone help me identify what I might be doing wrong? Thanks in advance! ...

Encountering a challenge in Angular 8: Unable to locate a supporting object matching '[object Object]'

I am having an issue trying to retrieve the Spotify API from the current user's playlists. While I can see it in my console, when I attempt to insert it into HTML, I encounter the following error: ERROR Error: Cannot find a differ supporting object ...

Effortlessly move and place items across different browser windows or tabs

Created a code snippet for enabling drag and drop functionality of elements within the same window, which is working smoothly. var currentDragElement = null; var draggableElements = document.querySelectorAll('[draggable="true"]'); [].forEach ...

AngularJS - development of a service entity

After deliberating between posting in the Angular mailing list or seeking assistance from the JavaScript community, I have decided that this is more of a JavaScript question. Hopefully, the knowledgeable individuals on Stack Overflow can provide a quicker ...

Instructions for arranging dropdown options alphabetically with html, vue, and js

When working with JavaScript, is there a method to populate an options list from a database and then sort it alphabetically? ...

Challenges compiling 'vue-loader' in Webpack caused by '@vue/compiler-sfc' issues

The Challenge Embarking on the development of a new application, we decided to implement a GULP and Webpack pipeline for compiling SCSS, Vue 3, and Typescript files. However, my recent endeavors have been consumed by a perplexing dilemma. Every time I add ...

What is the best approach for sending a binary image post request to an API using nodejs?

I am receiving the image binary in this manner: axios.get("image-url.jpg") Now, I want to utilize the response to create a new POST request to another server const form = new FormData(); const url = "post-url-here.com"; form.appe ...

Tabbed form design using Twitter Bootstrap

Currently, I am working on a website using the Bootstrap framework. My goal is to create a single page that features a pop-up form with two or three tabs. Specifically, I envision these tabs as "The Markup," "The CSS," and "The JavaScript." While I have ma ...