Execute multiple AJAX request parallel without waiting for others to respond

ajax, jquery, multithreading

Solution

you first code sample guarantees to run the code when any AJAX request is completed and CPU is free to use. Do NOT forget the JS engine is single thread and it queues tasks to do when CPU is free.

if your first completed AJAX request (A1) takes 10 seconds to run and during this time the second AJAX request (A2) get completed, A2 has to wait because CPU is processing the code for A1.

You can find more details in this https://www.youtube.com/watch?v=8aGhZQkoFbQ. In this video Philip Roberts describes how event loops are working in browsers.

Problem

I have the problem that i need to execute multiple AJAX requests on one Page. The request start all at the same time but they seem to wait for their predecessor to return. Lets say that page1 needs about 3 seconds to load. And page2 needs 2 seconds to load. What i get is that both start at the same time and the page1 request returns after 3 secons. But the problem is that the page2 request returns after 5 seconds. Why is that so ? I thought that every AJAX request will run in it's own thread. So why do the queue? Why does the second one waits for the first one to respond befor it even seem to start? How do I manage to send both requests and process each respond as soon as it arrives ? ``` $.ajax({ type: "POST", url: 'page1.php', data: { } }) .done(function( data ) { console.log(data); }); $.ajax({ type: "POST", url: 'page2.php', data: { } }) .done(function( data ) { console.log(data); }); ``` I see a lot of examples using this approach. ``` $.when( $.get("/resource1"), $.get("/resource2"), $.get("/resource3") ).done(function(response1, response2, response3) { // do things with response1, response2 and response3; }); ``` But as far as i understand this it will process the responses as soon as all of them returned. Any ideas on this one ?

Original source