Skip to content

Instantly share code, notes, and snippets.

@spadgos
Created March 3, 2014 09:20
Show Gist options
  • Save spadgos/9321318 to your computer and use it in GitHub Desktop.
Save spadgos/9321318 to your computer and use it in GitHub Desktop.
Promises causing memory leaks
function bad() {
var promise = somethingAsync();
promise.finally(function () {
logSomeThings();
});
promise = promise.then(function (result) {
return transform(result);
});
return promise;
}
function good() {
var promise = somethingAsync();
promise = promise.finally(function () { // <-- only changed line
logSomeThings();
});
promise = promise.then(function (result) {
return transform(result);
});
return promise;
}
@spadgos
Copy link
Author

spadgos commented Mar 3, 2014

This is using Q. The somethingAsync method essentially returns Q.defer().promise

@kriskowal
Copy link

I am not sure either, but the difference is that the original promise would not be retained. The same could be accomplished, I suspect, by writing promise = null in the handler. Does this pattern leak?

function maybe() {
    return somethingAsync()
    .finally(logSomeThings)
    .then(transform);
}

That should be equivalent, is the common usage, and doesn’t retain any intermediates. If that leaks, it’s bad news. (please ping on Twitter again; gist will not inform me if you reply).

@spadgos
Copy link
Author

spadgos commented Mar 3, 2014

@kriskowal: having some difficulty repro'ing the error right now (the original leak was very slow and was only visible under production load -- fun!). I'll trying boiling it down to the raw test case above and update tomorrow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment