如何添加延迟到现有$.when的新jquery

How can I add a new jquery deferred to an existing $.when?

本文关键字:when jquery 的新 迟到 延迟 何添加 添加      更新时间:2023-09-26

我正在重构一个资源加载函数,该函数使用传统的回调模式来代替jQuery Deferred。

此函数获取一个url数组,为每个资源创建一个新的Deferred对象,创建一个$.whenDeferred对象来监视它们,并返回$.when对象的promise。

以下是该方法的简化版本:

theLib = {
    getResources : function(paths) {
        var deferreds = [];
        theLib.isLoading = true;
        $.each(paths, function(i, path) {
            // do something with the path, either using getScript
            // or making a new $.Deferred as needed
            deferreds.push(/* the deferred object from above comment */);
        });
        theLib.currentDeferred = $.when.apply(null,deferreds).always(function() {
            theLib.isLoading = false;
        });
        return theLib.currentDeferred.promise();
};

这很有效。

我的问题是:在旧的脚本中,不仅会根据用户的操作或事件调用theLib.getResources(),而且还会定义一个资源的主列表,当用户不采取任何操作(即阅读文章)时,应用程序将"流式传输"这些资源。

其中一些流式资源与用户执行操作时可以手动调用的资源相同。该脚本足够聪明,通过跟踪加载的内容,不会两次加载资源。

它还跟踪theLib.isLoading。这个函数的开头看起来是这样的:

getResources : function(paths, callback) {
    if (theLib.isLoading) {
        settimeout(function() {
            theLib.getResources(paths, callback);
        }, 100);
    }
    theLib.isLoading = true;

我不能再这样做了,因为我需要返回一个promise对象。

我知道我可以检查theLib.currentDeferred.isResolved()。在这一点上,如果没有解决:如何向正在监视的$.when队列添加更多延迟对象?

我想我需要问这个问题来为自己找到解决方案。基本上,我在getResources的开头添加了以下代码:

if ( ! theLib.currentDeferred.isResolved()) { return $.when(theLib.currentDeferred).always(function() { theLib.getResources(paths); }).promise(); }

以上都是失败的。正确的解决方案是通过管道传输结果:

if ( ! theLib.currentDeferred.isResolved()) {
    return theLib.currentDeferred.pipe(function() {
        return theLib.getResources(paths);
    });
}