我是否应该总是调用JQuery Deferred.resolve或Deferred.reject? [英] Shall I always invoke either JQuery Deferred.resolve or Deferred.reject?
问题描述
因此,如下面的代码所示,它仅处理ajax调用成功的情况,如果ajax调用失败,则将其忽略,并且永远不会调用deferred.reject().因此,如果遇到失败的情况,jQuery内是否会永久保留任何事件侦听器,从而导致内存泄漏?
So as below code, it only deal with the ajax call success case, if the ajax call failed, it is ignored and the deferred.reject() will never be invoked. So if we meet the failed case, will there any event listener inside jQuery will be keep forever to cause memory leak?
$.when(loadSomething).done(function() {
// ...
});
function loadSomething() {
var deferred = $.Deferred();
// Only deal with the success case,
// If the ajax call failed, it is ignored and the deferred.reject() will never be invoked.
// So if we meet the failed case, will there any event listener inside jQuery will be keeped
// forever?
ajaxCallToLoad(onResult);
function onResult() {
deferred.resolve();
}
return deferred.promise();
}
推荐答案
因此,如果遇到失败的情况,jQuery内是否会永久保留任何事件侦听器,从而导致内存泄漏?
So if we meet the failed case, will there any event listener inside jQuery will be keep forever to cause memory leak?
几乎可以肯定.
但是,如果这样做,您将显式使用Promise语义,但随后违反了Promise合同.那是不好的做法.您必须具有最佳做法"选项:
But if you do that, you're explicitly using promise semantics but then breaking the promise contract. That's poor practice. You have to "best practices" options:
-
继续使用承诺,但要遵守合同.更新
ajaxCallToLoad
,以便它也通知您失败,并在发生延迟时对延迟的呼叫reject
. (如果ajaxCallToLoad
使用的是jQuery的$.ajax
函数,则可以使用$.ajax
返回的jqXHR
对象;它实现Promise
.)
Continue using promises, but stick to the contract. Update
ajaxCallToLoad
so that it also notifies you of failure, and callreject
on your deferred when that happens. (IfajaxCallToLoad
is using jQuery's$.ajax
function, you could just use thejqXHR
object that$.ajax
returns; it implementsPromise
.)
如果您不想履行承诺合同,只需使用常规的成功"回调而不是承诺即可.
If you don't want to fulfill the promise contract, just use a normal "success" callback rather than a promise.
这篇关于我是否应该总是调用JQuery Deferred.resolve或Deferred.reject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!