Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if await never returns? [duplicate]

In ECMAScript I am using CancelablePromise (https://github.com/alkemics/CancelablePromise) that basically is just a Promise with a .cancel() function. Whenever .cancel() is called, the callbacks provided to .then() and .catch() are not executed.

I wonder what happens if I await on a cancelled promise:

CancelablePromise promise = new CancelablePromise((resolve, reject) => resolve(1));
const promise2 = promise.then(x => x + 1);
promise.cancel();
console.log(await promise2);

So this code works as expected, nothing is printed on console. However, I wonder if this creates any hanging threads / references that cannot be collected by the GC or is this perfectly safe and valid to use?

like image 281
Flo Avatar asked Jan 04 '23 18:01

Flo


1 Answers

await is just syntactical sugar on top of promises. It's analogous to a p.then() statement in ES6. In ES6, if the promise never resolves, then the code inside the .then() handler never executes. With await, the interpreter essential puts the following code block inside an automatically created .then() handler. Internally, it pretty much works the same way.

There are no extra threads left running. await doesn't use threads. Depending upon exactly why the promise never resolves, the promise itself likely never gets GCed because internally, there's probably still a reference to it by the underlying code that "could" resolve it at some point in the future.

While this isn't a disaster, it's probably not a good design. If there's some condition where the promise may never resolve, then you should probably at least use a timeout and clear references to the promise or find a way to cancel the underlying operation. Without specific details to what the operation actually is, we can't provide more specific recommendations.

like image 85
jfriend00 Avatar answered Jan 08 '23 06:01

jfriend00