I have a Promise
. I created it to cancel an AJAX request if needed. But since I don't need to cancel that AJAX, I've never resolved it and AJAX completed successfully.
A simplified snippet:
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
life cycle?
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:
And then watching the heap itself. As we can see in the Chrome profiling tools, this accumulates the needed memory to allocate a 100 promises and then just "stays there" at less than 15 megabyes for the whole JSFIddle page
From the other side, if we look at the
$q
source codeWe 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.
So after the initial allocation - it seems like it's able to handle that as well :)
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