对ajax请求进行排序

时间:2010-06-14 03:51:12

标签: javascript jquery ajax design-patterns queue

我发现我有时需要迭代一些集合并为每个元素进行ajax调用。我希望在转移到下一个元素之前返回每个调用,这样我就不会向服务器发送请求 - 这通常会导致其他问题。我不想将异步设置为false并冻结浏览器。

通常这涉及设置某种迭代器上下文,我逐步完成每个成功回调。我认为必须有一种更简洁的方式吗?

有没有人有一个聪明的设计模式,如何通过一个集合为每个项目调用ajax来整齐地工作?

9 个答案:

答案 0 :(得分:110)

jQuery 1.5 +

我开发了一个$.ajaxQueue()插件,该插件使用$.Deferred.queue()$.ajax()来传回请求完成时已解析的promise

/*
* jQuery.ajaxQueue - A queue for ajax requests
* 
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
*/ 
(function($) {

// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});

$.ajaxQueue = function( ajaxOpts ) {
    var jqXHR,
        dfd = $.Deferred(),
        promise = dfd.promise();

    // queue our ajax request
    ajaxQueue.queue( doRequest );

    // add the abort method
    promise.abort = function( statusText ) {

        // proxy abort to the jqXHR if it is active
        if ( jqXHR ) {
            return jqXHR.abort( statusText );
        }

        // if there wasn't already a jqXHR we need to remove from queue
        var queue = ajaxQueue.queue(),
            index = $.inArray( doRequest, queue );

        if ( index > -1 ) {
            queue.splice( index, 1 );
        }

        // and then reject the deferred
        dfd.rejectWith( ajaxOpts.context || ajaxOpts,
            [ promise, statusText, "" ] );

        return promise;
    };

    // run the actual query
    function doRequest( next ) {
        jqXHR = $.ajax( ajaxOpts )
            .done( dfd.resolve )
            .fail( dfd.reject )
            .then( next, next );
    }

    return promise;
};

})(jQuery);

jQuery 1.4

如果您正在使用jQuery 1.4,则可以利用空对象上的动画队列为您的元素的ajax请求创建自己的“队列”。

您甚至可以将其纳入您自己的$.ajax()替代品中。这个插件$.ajaxQueue()使用jQuery的标准'fx'队列,如果队列尚未运行,它将自动启动第一个添加的元素。

(function($) {
  // jQuery on an empty object, we are going to use this as our Queue
  var ajaxQueue = $({});

  $.ajaxQueue = function(ajaxOpts) {
    // hold the original complete function
    var oldComplete = ajaxOpts.complete;

    // queue our ajax request
    ajaxQueue.queue(function(next) {

      // create a complete callback to fire the next event in the queue
      ajaxOpts.complete = function() {
        // fire the original complete if it was there
        if (oldComplete) oldComplete.apply(this, arguments);

        next(); // run the next query in the queue
      };

      // run the query
      $.ajax(ajaxOpts);
    });
  };

})(jQuery);

使用示例

所以,我们有一个<ul id="items">,其中有一些<li>我们想要复制(使用ajax!)到<ul id="output">

// get each item we want to copy
$("#items li").each(function(idx) {

    // queue up an ajax request
    $.ajaxQueue({
        url: '/echo/html/',
        data: {html : "["+idx+"] "+$(this).html()},
        type: 'POST',
        success: function(data) {
            // Write to #output
            $("#output").append($("<li>", { html: data }));
        }
    });
});

jsfiddle demonstration - 1.4 version

答案 1 :(得分:13)

使用延期承诺的快速小解决方案。虽然这使用jQuery的$.Deferred,但任何其他人都应该这样做。

var Queue = function () {
    var previous = new $.Deferred().resolve();

    return function (fn, fail) {
        return previous = previous.then(fn, fail || fn);
    };
};

用法,调用创建新队列:

var queue = Queue();

// Queue empty, will start immediately
queue(function () {
    return $.get('/first');
});

// Will begin when the first has finished
queue(function() {
    return $.get('/second');
});

请参阅the example,并对异步请求进行并排比较。

答案 2 :(得分:3)

您可以将所有复杂性包装到函数中,以进行如下所示的简单调用:

loadSequantially(['/a', '/a/b', 'a/b/c'], function() {alert('all loaded')});

下面是一个粗略的草图(工作示例,除了ajax调用)。这可以修改为使用类似队列的结构而不是数组

  // load sequentially the given array of URLs and call 'funCallback' when all's done
  function loadSequantially(arrUrls, funCallback) {
     var idx = 0;

     // callback function that is called when individual ajax call is done
     // internally calls next ajax URL in the sequence, or if there aren't any left,
     // calls the final user specified callback function
     var individualLoadCallback = function()   {
        if(++idx >= arrUrls.length) {
           doCallback(arrUrls, funCallback);
        }else {
           loadInternal();
        }
     };

     // makes the ajax call
     var loadInternal = function() {
        if(arrUrls.length > 0)  {
           ajaxCall(arrUrls[idx], individualLoadCallback);
        }else {
           doCallback(arrUrls, funCallback);
        }
     };

     loadInternal();
  };

  // dummy function replace with actual ajax call
  function ajaxCall(url, funCallBack) {
     alert(url)
     funCallBack();
  };

  // final callback when everything's loaded
  function doCallback(arrUrls, func)   {
     try   {
        func();
     }catch(err) {
        // handle errors
     }
  };

答案 3 :(得分:3)

理想情况下,一个具有多个入口点的协程,因此服务器的每个回调都可以调用相同的协程。该死的,这将在Javascript 1.7中实现。

让我尝试使用封闭......

function BlockingAjaxCall (URL,arr,AjaxCall,OriginalCallBack)
{    
     var nextindex = function()
     {
         var i =0;
         return function()
         {
             return i++;
         }
     };

     var AjaxCallRecursive = function(){
             var currentindex = nextindex();
             AjaxCall
             (
                 URL,
                 arr[currentindex],
                 function()
                 {
                     OriginalCallBack();
                     if (currentindex < arr.length)
                     {
                         AjaxCallRecursive();
                     }
                 }
             );
     };
     AjaxCallRecursive();    
}
// suppose you always call Ajax like AjaxCall(URL,element,callback) you will do it this way
BlockingAjaxCall(URL,myArray,AjaxCall,CallBack);

答案 4 :(得分:2)

是的,虽然其他答案都有效,但它们的代码很多,看起来很乱。 Frame.js旨在优雅地解决这种情况。 https://github.com/bishopZ/Frame.js

例如,这会导致大多数浏览器挂起:

for(var i=0; i<1000; i++){
    $.ajax('myserver.api', { data:i, type:'post' });
}

虽然这不会:

for(var i=0; i<1000; i++){
    Frame(function(callback){
        $.ajax('myserver.api', { data:i, type:'post', complete:callback });
    });
}
Frame.start();

此外,使用Frame允许您在完成整个AJAX请求系列之后(如果您愿意)将响应对象置于瀑布并处理它们:

var listOfAjaxObjects = [ {}, {}, ... ]; // an array of objects for $.ajax
$.each(listOfAjaxObjects, function(i, item){
    Frame(function(nextFrame){ 
        item.complete = function(response){
            // do stuff with this response or wait until end
            nextFrame(response); // ajax response objects will waterfall to the next Frame()
        $.ajax(item);
    });
});
Frame(function(callback){ // runs after all the AJAX requests have returned
    var ajaxResponses = [];
    $.each(arguments, function(i, arg){
        if(i!==0){ // the first argument is always the callback function
            ajaxResponses.push(arg);
        }
    });
    // do stuff with the responses from your AJAX requests
    // if an AJAX request returned an error, the error object will be present in place of the response object
    callback();
});
Frame.start()

答案 5 :(得分:2)

我发布这个答案,认为它可能在将来帮助其他人,在同一场景中寻找一些简单的解决方案。

现在也可以使用ES6中引入的本机承诺支持。您可以将ajax调用包装在promise中,并将其返回给元素的处理程序。

function ajaxPromise(elInfo) {
    return new Promise(function (resolve, reject) {
        //Do anything as desired with the elInfo passed as parameter

        $.ajax({
            type: "POST",
            url: '/someurl/',
            data: {data: "somedata" + elInfo},
            success: function (data) {
                //Do anything as desired with the data received from the server,
                //and then resolve the promise
                resolve();
            },
            error: function (err) {
                reject(err);
            },
            async: true
        });

    });
}

现在以递归方式调用函数,从中获取元素集合。

function callAjaxSynchronous(elCollection) {
    if (elCollection.length > 0) {
        var el = elCollection.shift();
        ajaxPromise(el)
        .then(function () {
            callAjaxSynchronous(elCollection);
        })
        .catch(function (err) {
            //Abort further ajax calls/continue with the rest
            //callAjaxSynchronous(elCollection);
        });
    }
    else {
        return false;
    }
}

答案 6 :(得分:1)

我使用http://developer.yahoo.com/yui/3/io/#queue来获取该功能。

正如您所说,我能提出的唯一解决方案是维护待处理呼叫/回调列表。或者在前一个回调中嵌套下一个调用,但感觉有点乱。

答案 7 :(得分:1)

您可以使用then实现相同的目标。

var files = [
  'example.txt',
  'example2.txt',
  'example.txt',
  'example2.txt',
  'example.txt',
  'example2.txt',
  'example2.txt',
  'example.txt'
];

nextFile().done(function(){
  console.log("done",arguments)
});

function nextFile(text){
  var file = files.shift();
  if(text)
    $('body').append(text + '<br/>');
  if(file)
    return $.get(file).then(nextFile);
}

http://plnkr.co/edit/meHQHU48zLTZZHMCtIHm?p=preview

答案 8 :(得分:1)

我建议使用一种更复杂的方法,该方法可在不同情况下重用。
例如,当用户在文本编辑器中键入内容时需要放慢通话顺序时,可以使用它。

但是我确信它在遍历集合时也应该起作用。在这种情况下,它可以将请求排队,并且可以发送一个AJAX调用而不是12。

queueing = {
    callTimeout:                 undefined,
    callTimeoutDelayTime:        1000,
    callTimeoutMaxQueueSize:     12,
    callTimeoutCurrentQueueSize: 0,

    queueCall: function (theCall) {
        clearTimeout(this.callTimeout);

        if (this.callTimeoutCurrentQueueSize >= this.callTimeoutMaxQueueSize) {
            theCall();
            this.callTimeoutCurrentQueueSize = 0;
        } else {
            var _self = this;

            this.callTimeout = setTimeout(function () {
                theCall();
                _self.callTimeoutCurrentQueueSize = 0;
            }, this.callTimeoutDelayTime);
        }

        this.callTimeoutCurrentQueueSize++;
    }
}
相关问题