gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:06:36 26 4
gpt4 key购买 nike

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

此函数获取 url 数组,为每个资源创建一个新的 Deferred 对象,创建一个 $.when Deferred 对象来监视它们,并返回 $.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()) {
返回 $.when(theLib.currentDeferred).always(function() {
theLib.getResources(路径);
})。 promise ();
}

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

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

关于javascript - 如何添加延迟到现有 $.when 的新 jquery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6243264/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com