A wrapper to make promises cancellable and garbage collectable
npm install trashable




A wrapper to make promises cancellable and garbage collectable. See how this
relates to React below and use [trashable-react][trashable-react] to
make your React components garbage collectable.
``bash`
npm install --save trashable
`es6
import makeTrashable from 'trashable';
let promise = new Promise((resolve) => {
setTimeout(resolve, 10000);
});
let trashablePromise = makeTrashable(promise);
trashablePromise.then(() => {
console.log('10 seconds have passed');
});
trashablePromise.trash();
`
> You wanted a banana but what you got was a gorilla holding the banana and the
> entire jungle.
>
> — Joe Armstrong
The handlers you pass to promises often reference other objects. These objects
can be quick large. This means if the promise is still in flight (not resolved
or rejected), these large objects cannot be safely garbage collected even when
the promise result has been forgotten and been ignored. That is why canceling
promises so that the objects their handlers reference can be freed is so
important.
In particular, this issue has reared its head in React with the use of
isMount() method (now deprecated). [This article][react-ismounted-antipattern]isMount()
gives a good explanation for why using should be avoided. Simply
put, prevents a garbage collector from getting rid of potentially large React
Elements.
It recommends to clean up any callbacks in componentWillUnmount so that theysetState()
won't call after the element has been unmounted and thus continue
to reference the Element.
Unfortunately, this is not that easy if promises are used and the solution it
provides in that article actually doesn't solve the garbage collection problem.
The cancel method does nothing to dereference the handlers and the Element will
not be garbage collected (see more in the PROOF).
Use [trashable-react][trashable-react] to make your React components garbage
collectable.
Unlike other cancelable promise libraries, Trashable actually dereferences the
promise handlers so that objects that were referenced can be garbaged collected
appropriately, freeing up memory.
You need to make your promises trashable before you add your then andcatch handlers. Otherwise, you will not get the garbage collection benefits.
`es6
// Do this
const trashablePromise = makeTrashable(promise);
trashablePromise.then(() => {});
// NOT this
const handledPromise = promise.then(() => {});
makeTrashable(handledPromise);
``
* @istarkov's solution
* @benmmurphy's solution
[react-ismounted-antipattern]: https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html
[trashable-react]: https://github.com/hjylewis/trashable-react