【问题标题】:How can I add a new jquery deferred to an existing $.when?如何添加延迟到现有 $.when 的新 jquery?
【发布时间】:2011-06-05 13:37:26
【问题描述】:

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

此函数接受 url 数组,为每个资源创建一个新的 Deferred 对象,创建一个 $.when Deferred 对象来监视它们,并返回 $.when 对象的承诺。

这是该方法的简化版本:

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 队列?

【问题讨论】:

    标签: javascript jquery jquery-deferred


    【解决方案1】:

    我想我需要提出这个问题才能为自己找到解决方案。基本上我在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);
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      相关资源
      最近更新 更多