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

When an image in AngularJS is clicked, it should display a corresponding list

I'm brand new to Angular development. This is my very first solo project. My goal is to design a page where clicking on an image will display a list of items below it. For example, check out this link for reference: I've searched online for so ...

jQuery does not allow for text input values to be posted

Having an issue with a form using the POST method. I have some PHP controls that are being calculated in jQuery. While all the form control values are accessible in the next form using POST, the values added through jQuery are not posting to the next form. ...

I am wondering how to use the value assigned to a variable's textContent as an argument for player input in my JavaScript code

i am currently developing a JavaScript project to create a user interface for my rock, paper, scissors game. Currently, the game only runs in the console and prompts the player for input. So far, I have implemented three buttons (one each for rock, paper, ...

Experiencing a JSONP issue with an 'Access-Control-Allow-Origin' error

When working with PHP, I often use the following code to echo JSONP formatted data: echo $_GET['callback'] . '('.json_encode($arr).')'; In my AngularJS (JavaScript) code, I make a GET request like this: $http.get('http ...

Best practice for triggering events based on mysql datetime with the help of ajax

Currently engaged in a CRM project aimed at creating a user-friendly backoffice system where clients can be added and events such as follow-ups and SLA controls can be defined. The goal is to trigger notifications on the webpage only for new events. For e ...

The registration feature powered by JQuery is experiencing technical difficulties and not functioning

Having trouble with a registration system on my website at *. When someone registers, it should either show an error message or display "true" if the registration is successful. I have a javascript file (http://pastebin.com/mv9CWZcT) set up to redirect the ...

Troubleshooting Problems with CSS `transform` in JQuery UI's `Slide` Transition

While implementing JQueryUI's slide transition on an element with a CSS transform, I encountered an issue where the top half of the element gets hidden during the animation. Is there a way to tweak either my JQueryUI animation or CSS to avoid this pro ...

What is the best way to have a text field automatically insert a hyphen after specific numbers?

Is there a way to make a text field insert hyphens automatically after certain numbers? For example, when typing a date like 20120212, could we have the input automatically formatted with hyphens after the first 4 digits and the second two, so it displays ...

Scrolling text blocks on mobile devices

When viewing the website on a desktop, everything works perfectly. However, when accessing it on a mobile device and trying to scroll down, only the text moves while the page remains stationary. The website utilizes skrollr core for animations. I have alre ...

Preserve file sequence with jquery file upload

I recently came across an interesting upload script at the following link: This script utilizes jquery file upload to allow for uploading multiple files simultaneously. I'm curious about how to transmit the order in which the files were selected to t ...

Invoking a JavaScript function within an ASP Repeater

I am looking to incorporate a JavaScript function into an ASPX page within Visual Studios 2012. This function is designed to retrieve 7 values from a database multiple times and dynamically adjust the CSS based on these values. Additionally, it targets a s ...

Utilize Material-UI's <Autocomplete /> feature to conduct searches using multiple parameters

Recently, I started delving into mastering Material UI and something has been on my mind. We are working with an array of objects as follows: const top100Films = [ { label: 'The Shawshank Redemption', year: 1994 }, { label: 'The Godfath ...

Error Alert: jQuery Ajax Not Executing

Looking to send form data to PHP using jQuery. Check out the code below. -------------HTML FORM-------------- <div id="createQuestionBlock"> <form id="createQuestionForm" action="" method="POST"> Question Code: <input id="code" ...

How to securely upload and generate a permanent link for the contents of a zip file using express js

I am new to Javascript and Node JS. I have a challenge of uploading a zip file containing only pictures and creating permanent links for these pictures. Currently, I can upload a zip file and extract its contents using the following code snippet: var expr ...

Controlling File Upload Edits: A Guide to Effective Management

I am facing an issue on my product page related to adding and updating products in the database. The problem lies with images not displaying correctly. During the product insertion process, everything works fine. In my aspx page, I have the following code ...

Moving punctuation from the beginning or middle of a string to the end: A guide

My Pig Latin converter works well with single or multi-word strings, but it struggles with punctuation marks. For example, when I input translatePigLatin("Pig Latin.");, the output is 'Igpay Atin.lay' instead of 'Igpay Atinlay.'. How c ...

Executing an external function on an element as soon as it is created in AngularJS: tips and tricks

I am looking to implement a function from an external library that will be executed on each item as it is created in AngularJS. How can I achieve this? Here is the code snippet of my application. var app = angular.module('app', []); app.contr ...

Can we find a different way to address this issue with a "functional programming" mindset that doesn't involve utilizing the `forEach` method?

There has been a discussion about whether or not we still need to use forEach in JavaScript due to the availability of new language features. Some have suggested that this shift is an indirect push towards functional programming. I recently came across an ...

How can I append an object key to the end of a URL link within an anchor tag

I seem to be facing a problem where I am attempting to append the key of my object at the end of a URL. It appears to work fine as a button, but for some reason the key is not being displayed within the href attribute. Typically, I would use "+" to conca ...

Tips for implementing a search function with DynamoDB using the "contains" operator

I'm currently working on implementing a search function in my React application. Here is the structure of my DynamoDB table: --------------------- movie_id | movie_name --------------------- 1 | name a --------------------- 2 | name b ...