javascript 排队 AJAX 调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4797566/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Queue AJAX calls
提问by Will Hancock
Hello I am doing a Horizontal scrolling website like: http://vanityclaire.com/
你好,我正在做一个水平滚动的网站,如:http: //vanityclaire.com/
However, rather than having one large HTML file, after the load of the homepage, I am ajaxing in the children of home, using jQuery .load().
但是,在加载主页之后,我没有使用一个大的 HTML 文件,而是使用 jQuery .load() 在 home 的孩子中进行 ajaxing。
At present I for-each div and ajax in ithe url that sits in the title. But the AJAX returns out of order, and as I add more pages don't fancy spangingthe server with 30+ http:// requests.
目前,我在标题中的 url 中为每个 div 和 ajax。但是 AJAX 返回乱序,当我添加更多页面时,我不想用 30 多个 http:// 请求跨越服务器。
How do I synchronously do the AJAX calls, i.e. wait for the first to comeback before a request another, or even send two at a time.
我如何同步执行 AJAX 调用,即在请求另一个之前等待第一个返回,甚至一次发送两个。
I have been scouring, and cannot figure out what I need.
我一直在搜索,无法弄清楚我需要什么。
This is my HTML:
这是我的 HTML:
<div id="mainLayout" class="fullwidth scrollArea">
    <div class="scrollItems">
      <div id="page-1" class="scrollItem" title="/">
        <div>HOME PAGE CONTENT</div>
      </div>
      <div id="page-2" class="scrollItem" title="/Page2.html">
        <div class="loading"> </div>
      </div>
      <div id="page-3" class="scrollItem" title="/Page3.html">
        <div class="loading"> </div>
      </div>
      <div id="page-4" class="scrollItem" title="/Page4.html">
        <div class="loading"> </div>
      </div>
      <div id="page-5" class="scrollItem" title="/Page5.html">
        <div class="loading"> </div>
      </div>
    </div>
  </div>
And my JS:
还有我的 JS:
function s_loadingInitialPages() {
    var loadingItems = new Array();
    $(".scrollArea .scrollItem").each(function () {
        if ($(this).attr('title') != '/') {
            var oDelem = $(this);
            loadingItems.push(oDelem);
            //alert('test');
        }
    });
    for (i = 0; i < loadingItems.length; i++) {
        // title attribute is the URL to get
        var ajaxURL = loadingItems[i].attr("title") + '?ajaxPageContent=';
        $(loadingItems[i]).load(ajaxURL);
    }
}
Is there a plugin I can just keep adding functions to a queue, and let that handle it?
有没有插件可以让我继续向队列添加函数,然后让它处理它?
回答by Raynos
The trick is to use the callbacks. You make one ajax call and on its success callback you make the next one.
诀窍是使用回调。您进行一次 ajax 调用,并在其成功回调时进行下一次调用。
To do this just add them all to a queue and have a wrapper around it that sends them one by one.
要做到这一点,只需将它们全部添加到一个队列中,并在其周围放置一个包装器,将它们一一发送。
I wrote one a few days ago. I'll show you an implementation in a second.
我前几天写了一篇。稍后我将向您展示一个实现。
// Buffer class. Has a public append method that expects some kind of Task.
// Constructor expects a handler which is a method that takes a ajax task
// and a callback. Buffer expects the handler to deal with the ajax and run
// the callback when it's finished
function Buffer(handler) {
    var queue = [];
    function run() {
        var callback = function () {
             // when the handler says it's finished (i.e. runs the callback)
             // We check for more tasks in the queue and if there are any we run again
             if (queue.length > 0) {
                  run();
             }
        }
        // give the first item in the queue & the callback to the handler
        handler(queue.shift(), callback);
    } 
    // push the task to the queue. If the queue was empty before the task was pushed
    // we run the task.
    this.append = function(task) {
        queue.push(task);
        if (queue.length === 1) {
            run();
        }
    }
}
// small Task containing item & url & optional callback
function Task(item, url, callback) {
    this.item = item;
    this.url = url;
    this.callback = callback
}
// small handler that loads the task.url into the task.item and calls the callback 
// when its finished
function taskHandler(task, callback) {
    $(task.item).load(task.url, function() {
        // call an option callback from the task
        if (task.callback) task.callback();
        // call the buffer callback.
        callback();
    });
}
// create a buffer object with a taskhandler
var buffer = new Buffer(taskHandler);
for (i = 0; i < loadingItems.length; i++) {
    // title attribute is the URL to get
    var ajaxURL = loadingItems[i].attr("title") + '?ajaxPageContent=';
    buffer.append(new Task(loadingItems[i], ajaxURL));
}
Apologies for the wall of code. Just implement your own Task and Handler. The Buffer will work as long as the handler calls the second argument (the callback) when it's finished handling the task.
为代码墙道歉。只需实现您自己的任务和处理程序。只要处理程序在完成处理任务时调用第二个参数(回调),缓冲区就会工作。
Then just pass it a task and a handler. The handler does the ajax and calls the callback from the buffer when the ajax returns.
然后只需向它传递一个任务和一个处理程序。处理程序执行 ajax 并在 ajax 返回时从缓冲区调用回调。
For your specific example if what your loading takes a long time then this will take a long time to load all 30. The point of ajax is to have the server do stuff in parallel.
对于您的具体示例,如果您的加载需要很长时间,那么加载所有 30 个需要很长时间。ajax 的重点是让服务器并行执行操作。
A far better solution in your case is to make 30 requests and then catch the results and make sure the results from your ajax calls are only appended to the dom in order. This involves using $.ajax and adding keeping track of order somehow.
在您的情况下,更好的解决方案是发出 30 个请求,然后捕获结果并确保 ajax 调用的结果仅按顺序附加到 dom。这涉及使用 $.ajax 并以某种方式添加跟踪订单。
That way the server will do it as fast as it can and you can server it in order once you get it. Alternatively if the things your doing are fast then queuing them in a buffer has no penalty.
这样服务器就会尽可能快地完成它,一旦你得到它,你就可以按顺序提供它。或者,如果你做的事情很快,那么在缓冲区中排队也不会受到惩罚。
回答by Jason Williams
Most browsers can handle 6 or more simultaneous ajax requests to a single domain.
http://www.browserscope.org/?category=network&v=top
大多数浏览器可以同时处理 6 个或更多对单个域的 ajax 请求。
http://www.browserscope.org/?category=network&v=top
If your script places 30 ajax requests at once, the first 6 requests will go through very quickly. After that, the browser may start assigning arbitrary wait periods of up to 5 seconds. Chrome is a prime example of this behavior.
如果您的脚本一次发出 30 个 ajax 请求,那么前 6 个请求将很快通过。之后,浏览器可能会开始分配最多 5 秒的任意等待时间。Chrome 是这种行为的一个典型例子。
Requests 1-6 return in 5 ms.
请求 1-6 在 5 毫秒内返回。
Requests 7-12 return in 5,005 ms.
请求 7-12 在 5,005 毫秒内返回。
Requests 11-18 return in 10,005 ms.
请求 11-18 在 10,005 毫秒内返回。
Requests 19-24 return in 15,005 ms.
请求 19-24 在 15,005 毫秒内返回。
Requests 25-30 return in 20,005 ms.
请求 25-30 在 20,005 毫秒内返回。
I recommend building a queue of function callbacks to handle all of your application's ajax requests and process no more than 6 of them at a time.
我建议构建一个函数回调队列来处理应用程序的所有 ajax 请求,并且一次处理不超过 6 个。
var ajaxCownt = (ajaxCownt == null ? 0 : ajaxCownt);  // Make limit globally accessible.
var ajaxKue = (ajaxKue == null ? [] : ajaxKue);  // Make queue globally accessible.
function doMyAjaxRequest() {
console.log("doing ajax request.");
// Implement ajax request, here.
}
for (var i = 1;i <= 30;i++) {
ajaxKue.push( function() { doMyAjaxRequest() } ); // Add request to queue.
}
while (ajaxCownt != null && ajaxCownt < 6 && ajaxKue != null && ajaxKue.length && ajaxKue.length > 0) {
ajaxCownt++;
console.log("incrementing pending ajax requests counter by 1.");
ajaxKue.shift().call();
};
// Register an event to detect when an ajax request completes.
// Allow for an additional ajax request to be processed.
$( document ).ajaxComplete(function() {
    if (ajaxCownt && ajaxCownt > 0) {
        ajaxCownt--;
        console.log("decrementing pending ajax requests counter by 1.");
    }
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
