难道未曾解决的承诺导致内存泄漏? [英] Do never resolved promises cause memory leak?

查看:202
本文介绍了难道未曾解决的承诺导致内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个承诺。我创建它,如果我需要取消一个AJAX请求。但因为我并不需要取消AJAX,我从来没有解决它和AJAX顺利完成。

I have a promise. I created it to cancel an AJAX request if I need. But since I don't need to cancel that AJAX, I've never resolved it and AJAX completed successfully.

一个简单的sinippet:

A simplified sinippet:

var defer = $q.defer();
$http({url: 'example.com/some/api', timeout: defer.promise}).success(function(data) {
    // do something
});

// Never defer.resolve() because I don't need to cancel that ajax. What happens to this promise after request?

难道未曾解决的承诺一样,导致内存泄漏?你有关于如何管理承诺的生命周期有什么建议?

Do never resolved promises like that cause memory leaks? Do you have any advice about how to manage promise lifecycle?

推荐答案

好吧,我假设你不保持一个明确提到它,因为这将迫使它留分配。

Well, I'm assuming you don't keep an explicit reference to it since that would force it to stay allocated.

我能想到的最简单的测试实际上是分配了很多的承诺,而不是解决这些问题:

The simplest test I could think of is actually allocating a lot of promises and not resolving them:

var $q = angular.injector(["ng"]).get("$q");
setInterval(function () {
    for (var i = 0; i < 100; i++) {
        var $d = $q.defer();
        $d.promise;
    }
}, 10);

然后看着堆本身。正如我们可以在Chrome分析工具看,这积累所需要的内存来分配一个100的承诺,然后就停留在那里,在不到15 megabyes整个的的jsfiddle页面

从另一个方面,如果我们看一下 $ q 源$ C ​​$ C

From the other side, if we look at the $q source code

我们可以看到,有从全球指向任何特定的承诺,但只从承诺到它的回调没有提及。在code是非常可读的和明确的。让我们来看看,如果你有但是从回调应许的参考。

We can see that there is no reference from a global point to any particular promise but only from a promise to its callbacks. The code is very readable and clear. Let's see what if you do however have a reference from the callback to the promise.

var $q = angular.injector(["ng"]).get("$q");
console.log($q);
setInterval(function () {
    for (var i = 0; i < 10; i++) {
        var $d = $q.defer();
        (function ($d) { // loop closure thing
            $d.promise.then(function () {
                console.log($d);
            });
        })($d);
    }
}, 10);

因此​​,最初的分配后 - 现在看来似乎是能够处理,以及:)

So after the initial allocation - it seems like it's able to handle that as well :)

我们也可以看到GC的一些有趣的模式,如果我们让他的最后一个例子跑了几分钟。我们可以看到,它需要一段时间 - 但它能够清洁回调

We can also see some interesting patterns of GC if we let his last example run for a few more minutes. We can see that it takes a while - but it's able to clean the callbacks.

在短期 - 至少在现代的浏览器 - 你不必,只要担心悬而未决的承诺,因为你没有给他们的外部引用

In short - at least in modern browsers - you don't have to worry about unresolved promises as long as you don't have external references to them

这篇关于难道未曾解决的承诺导致内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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