Skip to content

Instantly share code, notes, and snippets.

@benmmurphy
Created March 16, 2017 17:45
Show Gist options
  • Save benmmurphy/aaf35a44a6e8a1fbae1764ebed9917b6 to your computer and use it in GitHub Desktop.
Save benmmurphy/aaf35a44a6e8a1fbae1764ebed9917b6 to your computer and use it in GitHub Desktop.
leak.js
var Promise = require('promise');
var weak = require('weak');
var makeCancelable = (promise) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then((val) =>
hasCanceled_ ? reject({isCanceled: true}) : resolve(val)
);
promise.catch((error) =>
hasCanceled_ ? reject({isCanceled: true}) : reject(error)
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
};
class Foo {
constructor(promise) {
promise.then(() => {
console.log("then called....", this);
});
}
}
var resolve;
var p = new Promise((_resolve, reject) => {
resolve = _resolve;
});
var res = makeCancelable(p);
var foo = new Foo(res.promise);
res.cancel();
res = null;
p = null;
var ref = weak(foo, function () {
console.log("foo gc'd");
});
foo = null;
console.log("first gc", ref);
global.gc();
global.gc(); /* just in case it takes two gcs :) */
console.log("after first gc", ref);
/* no console.log... */
/* kill the resolve chain */
resolve = null;
console.log("after resolve = null", ref);
global.gc();
console.log("after second gc", ref);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment