Execute multiple AJAX request parallel without waiting for others to respond

梦想与她 提交于 2021-02-10 03:01:58

问题


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 ?


回答1:


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.




回答2:


Give async:true The request will be processed invidually!

$.ajax({
            url: 'test.html',
            async: true,
            success: function (data) { alert(data); }
        });



回答3:


If you are using PHP and file-based sessions, you may be limited to a single request per (PHP) page. You must close the session for multiple requests to be processed at the same time. See https://stackoverflow.com/a/8065977/1620112 for a solution to this.



来源:https://stackoverflow.com/questions/28691648/execute-multiple-ajax-request-parallel-without-waiting-for-others-to-respond

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!