有没有办法在延迟函数列表之一完成时触发 JQuery ?

Is there a way to fire JQuery .when on the moment that one of a list of deferred functions finishes?

我想使用 ajax 构建一个伪队列。
然后我想一次打五个电话。

伪代码类似于:

For each item in list as ajaxN{
FuncToRun.push(ajaxN);
If(count(FuncToRun)==5){
    .when (FuncToRun).onefinishes{
        FuncToRun.pop(success Func)
    }
}
}

这可能吗?

这听起来很像你想要的 jQuery.Callbacks

但是,Callbacks 对象不提供 length 属性 因此您需要想出一些机制来监视队列中函数的数量并在阈值 (5 ) 达到。

例如,您可以将回调对象包装在一个带有少量自定义方法和属性的小命名空间中。

var FunctionList = (function() {
    var list = $.Callbacks(),
        length = 0,
        threshold = 5;
    function add(fn) {
        if(fn  && $.isFunction(fn)) {
            list.add(fn);
            if(++length >= threshold) {
                list.fire().empty();
                length = 0;
            }
        }
        else {
            throw new TypeError("FunctionList.add() must be passed a function");
        }
    }
    function getLength(x) { return length; }
    function setThreshold(x) { threshold = x; }
    function getThreshold() { return threshold; }
    return {
        add: add,
        getLength: getLength,
        setThreshold: setThreshold,
        getThreshold: getThreshold
    };
})();

如上所写,FunctionList很基础,满足题的最低要求。可以进一步公开更多回调 API(例如标志、.disable().fireWith().has().lock().remove()).您还可以将命名空间重构为构造函数,允许同时使用多个 FunctionList

如何填充 FunctionList 由您决定。 FunctionList.add(...) 当然可以调用以响应 AJAX 成功,这正是您想要的。