javascript 用于对AJAX请求和其他异步任务进行排序的Javascript队列。演示http://jsfiddle.net/rusci/26Dud/6/

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 用于对AJAX请求和其他异步任务进行排序的Javascript队列。演示http://jsfiddle.net/rusci/26Dud/6/相关的知识,希望对你有一定的参考价值。

// Queue class for serializing AJAX calls.
//
// Inspired by Raynos http://stackoverflow.com/a/4797596/1194060
//
// Queue has a public append method that expects some kind of task.
// A task is a generic function passed as callback.
// Constructor expects a handler which is a method that takes a ajax task
// and a callback. Queue expects the handler to deal with the ajax and run
// the callback when it's finished

function Queue(handler) {
  var queue = [];

  function run() {
    var callback = function () {
      queue.shift();
      // 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[0], 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 handler that launch task and calls the callback 
// when its finished
var queue = new Queue(function (task, callback) {
  task(function () {
    // call an option callback from the task
    if (task.callback)
      task.callback();
    // call the buffer callback.
    console.log(task, ' done');
    callback();
  });
});


// Test 
// Add some tasks to queue...
var tasks = [
  function (callback) {
    setTimeout(function () {
      $('output').insert({
        bottom: '<li>Step 1 - ' + new Date() + '</li>'
      });
      callback();
    }, 1000);
  },
  function (callback) {
    setTimeout(function () {
      $('output').insert({
        bottom: '<li>Step 2 - ' + new Date() + '</li>'
      });
      callback();
    }, 3000);
  },
];

for (i = 0; i < tasks.length; i++) {
  queue.append(tasks[i]);
}

以上是关于javascript 用于对AJAX请求和其他异步任务进行排序的Javascript队列。演示http://jsfiddle.net/rusci/26Dud/6/的主要内容,如果未能解决你的问题,请参考以下文章

Ajax异步请求的步骤

JavaScript使用Ajax实现异步通信

前端基础——AJAX

JavaScript DOM 编程艺术之 Ajax

Ajax

ajax同步与异步的区别