在jQuery中排队可选的AJAX/函数调用($.Deferred)



我希望在JavaScript/jQuery中对任意数量的可能可选的函数调用进行排队。例如,在运行第二个(或第三个、第四个等)函数或AJAX调用之前,我可能需要确保用户经过身份验证并设置cookie。

我用最近添加的jQuery.Deferred进行了研究,但发现调用的启动顺序并不重要(真正的异步风格)。此外,我读到,一旦一个Deferred实例被解析,就不可能取消解析

这就是我现在的处境。最初,我考虑将Deferred实例设置为resolve,然后在堆栈中出现可选函数时取消解析。

var d = $.Deferred(),
    chained = d,
    d.resolve(),
    div = extra.find( "div:first" );
if ( extra.attr( "requires-auth" ) != undefined && !config.user_is_authenticated )
  chained = chained.pipe( authenticate );
if ( div.length )
  chained = chained.pipe( prepareExtra( div ) );
// When the two optional methods are resolved, show the content
chained.done( function() {
  extra.fadeIn( 500 )
} );

我的问题是,在纯JavaScript/jQuery中排队(0到N)AJAX调用的最佳方式是什么?(不使用插件)。

Tak!

编辑2:已解决以下是一些工作示例,一个没有AJAX,另一个带有:https://gist.github.com/1021429https://gist.github.com/1021435

尝试将您的初始Deferred解析为最后一件事:

var d = $.Deferred(),
    chained = d;
// optionally chain callbacks with chained = chained.pipe
if (condition) {
    chained = chained.pipe(function () {
        return $.ajax({...}); // Must return a new Promise
    });
}
chained.done(function () {
    // all chains should be processed now
});
d.resolve(); // finally, resolve the initial Deferred

使用序列助手:

https://github.com/michiel/asynchelper-js/blob/master/lib/sequencer.js

我也遇到过类似的问题:jQueryAjax。每次回调,next';每个';ajax完成前激发

我过去通过让ajax调用返回其他脚本来处理这个问题。对我来说,这是最好的解决方案。

然而,你想要一个纯粹的js方法,所以我会尝试一下。

var ScriptQueue = {
    scripts: [],
    readyToProcess: false,
    timer: null,
    stopTimer: function() {
        clearTimeout(ScriptQueue.timer);
        ScriptQueue.timer = null;
    },
    queue: function(functionToQueue) {
        ScriptQueue.stopTimer();
        ScriptQueue.scripts.push(functionToQueue);
        ScriptQueue.processNext();
    }, 
    processNext: function() {
       if (!readyToProcess || ScriptQueue.scripts.length == 0) {
           ScriptQueue.timer = setTimeout(ScriptQueue.processNext, 30000); // try again in 30 sec
       } else {
           ScriptQueue.stopTimer();
           var _function = ScriptQueue.scripts.shift();
           _function.call();
           ScriptQueue.processNext();
       }
    }
}
$(function(){
    // queue some stuff
    $('a').each(function() {
        ScriptQueue.queue(function() {
            console.info("running some link action");
        } );
    });
    // authorization
    $.ajax({
        url: yourURL
        success: function(data) {
           if (data == "correct response") {
               ScriptQueue.readyToProcess = true;
               ScriptQueue.processNext();
           }
        }
    })

});

我不知道这是否有效(未经测试),但我想提出一种可能的Deferred解决方案的替代方案(看起来很有希望)。也许这会导致进一步的讨论,也许会被忽视。

没有测试,但jQuery.when应该可以很好地工作:

var q = [];
function queue(promise, callback) {
    var ready = $.when.apply($, q); // resolves when all current elements 
                                   // of the queue have resolved
    q.push(promise);
    ready.done(function() {
        q.shift();
        var arg = Array.prototype.pop.call(arguments);
        callback.call(promise, arg);
    });
}

最新更新