Reputation: 10624
If I call multiple API using Ajax at the same time, it is very slow, it seems javascript waits until getting all API's responses, not getting response asynchronously.
For example, /api/test1 response in 5 sec in usual, and /api/test2 response in 5 sec in usual.
but if I call them at the same time, it takes 10 sec.
Example) it takes 10 sec
$.get("/api/test1", function() {
self.responseHandler1();
});
$.get("/api/test2", function() {
self.responseHandler2();
});
So to make it load faster I do for now,
$.get("/api/test1", function() { // 5 sec
self.responseHandler1();
$.get("/api/test2", function() { // 5 sec
self.responseHandler2();
});
});
But I think there is some nicer way, please advise me.
Upvotes: 1
Views: 1748
Reputation: 1
Your code
$.get("/api/test1", function() {
self.responseHandler1();
$.get("/api/test2", function() {
self.responseHandler2();
});
});
doesn't get test2 until test1 has been retrieved
This code
$.get("/api/test1", function() {
self.responseHandler1();
});
$.get("/api/test2", function() {
self.responseHandler2();
});
retrieves the two requests in parallel
and this code
$.when($.get("/api/test1"), $.get("/api/test2")).then(function(resp1, resp2) {
self.responseHandler1();
self.responseHandler2();
});
makes the requests in parallel, but runs both response handlers only once both requests have completed
as a test (regarding the changed 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 two values logged to console should be small numbers (easily less than 100) - if they are not, then your $.get
isn't asynchronous - my jQuery knowledge is hazy, but I think there's a way to make the default request synchronous, which may be what some part of your code has done - otherwise, the issue is with the server, perhaps it can't handle simultaneous requests, or perhaps whatever the api code is doing on the server is blocking - either way, if those to logged numbers are small, the problem exists with the server
Upvotes: 1