0

In modern Javascript, if I build up a sequence of actions inside promise.then(...).catch(...), but I don't care about the result, nor do I need to wait for the sequence to finish, but I do want it to finish, do I need to keep a reference to the resulting Promise? Is there a danger that it might be garbage-collected and never run to completion if I don't keep a reference to it alive?

If the answer is "this is implementation-dependent," that's disappointing. But I'd be especially interested to know how recent versions of V8 (≥ 9.5) handle this.

dubiousjim
  • 4,722
  • 1
  • 36
  • 34
  • there is no need to store the reference of the `promise` object if you are not going to use it. Just chain it and it will work as expected. – DecPK Nov 28 '21 at 02:27
  • 2
    Does this answer your question? [What happens to an ES6-Promise when you no longer hold a reference to it?](https://stackoverflow.com/questions/35638344/what-happens-to-an-es6-promise-when-you-no-longer-hold-a-reference-to-it) – Antonio Nov 28 '21 at 02:40
  • I think this might have a detailed answer: https://www.dankuck.com/2017/02/24/broken-js-promises.html – Antonio Nov 28 '21 at 02:47
  • The other questions @Antonio and shkaper link to are asking about the same issue, but don't give a clear definite answer. Still, presumably any answers could go there, rather than in a new question. – dubiousjim Nov 28 '21 at 07:14
  • The external link Antonio provides asserts that in `new Promise((resolve, rej) => {setTimeout(function funcB () {}, 10000);`, `funcB` will "retain a reference to `resolve`" until the timeout completes. I wish it had explained the evidence for that. Though these sources don't give a definitive answer, my overall impression from them is that yes, a promise chain might be GC'd before completion in some circumstances. – dubiousjim Nov 28 '21 at 07:19

1 Answers1

2

Do I need to keep a reference to a JS promise chain?

No, you do not. The promise chain will run to completion whether you save the promise or not.

Things are only garbage collected when they are no longer referenced by any active code. A promise that represents an active asynchronous operation is still being referenced by that asynchronous operation until that asynchronous operation is actually complete (since the asynchronous operation has the ability to resolve or reject the promise). So, promises won't be eligible for garbage collection until the operations they are connected to are done.

This is not implementation-dependent. The garbage collector cannot collect objects that are still in use. Everything would break if that was the case. Once the promise is no longer in use, then garbage collecting it has no affect on any running code.

jfriend00
  • 683,504
  • 96
  • 985
  • 979