我是否应该总是调用JQuery Deferred.resolve或Deferred.reject? [英] Shall I always invoke either JQuery Deferred.resolve or Deferred.reject?

查看:106
本文介绍了我是否应该总是调用JQuery Deferred.resolve或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:

  1. 继续使用承诺,但要遵守合同.更新ajaxCallToLoad,以便它也通知您失败,并在发生延迟时对延迟的呼叫reject. (如果ajaxCallToLoad使用的是jQuery的$.ajax函数,则可以使用$.ajax返回的jqXHR对象;它实现Promise.)

  1. Continue using promises, but stick to the contract. Update ajaxCallToLoad so that it also notifies you of failure, and call reject on your deferred when that happens. (If ajaxCallToLoad is using jQuery's $.ajax function, you could just use the jqXHR object that $.ajax returns; it implements Promise.)

如果您不想履行承诺合同,只需使用常规的成功"回调而不是承诺即可.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆