并行执行多个 AJAX 请求,无需等待其他人响应 [英] Execute multiple AJAX request parallel without waiting for others to respond

查看:44
本文介绍了并行执行多个 AJAX 请求,无需等待其他人响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了需要执行多个 AJAX 请求的问题在一页上.请求同时开始,但他们似乎在等待他们的前任返回.

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.

假设 page1 需要大约 3 秒才能加载.而 page2 需要 2 秒才能加载.我得到的是两者同时开始,并且 page1 请求在 3 秒后返回.

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.

但问题是page2请求5秒后返回.为什么会这样 ?我认为每个 AJAX 请求都会在它自己的线程中运行.那么为什么要排队呢?为什么第二个在它似乎开始之前等待第一个响应?

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.

对此有任何想法吗?

推荐答案

您的第一个代码示例保证在完成任何 AJAX 请求并且 CPU 空闲可以使用时运行代码.不要不要忘记 JS 引擎是单线程,它在 CPU 空闲时排队任务.

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.

如果第一个完成的 AJAX 请求 (A1) 运行需要 10 秒,而在此期间第二个 AJAX 请求 (A2) 完成,A2 必须等待,因为 CPU 正在处理 A1 的代码.

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.

您可以在此 https://www.youtube.com/watch?v 中找到更多详细信息=8aGhZQkoFbQ.在此视频中,Philip Roberts 介绍了事件循环在浏览器中的工作方式.

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.

这篇关于并行执行多个 AJAX 请求,无需等待其他人响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆