Say I have a promise called myProm
, and say I have success and error handlers called onSuccess
and onError
.
Whenever my promise takes longer than 10 seconds to complete, I want a function called timeoutHandler
to be executed, but if that happens, neither onSuccess
nor onError
should be executed. (Similarly, if either onSuccess
or onError
runs, I don't want my timeoutHandler
to be executed.)
I've come up with the following snippet for this.
new Promise((suc, err) => {
let outOfTime = false;
const timeoutId = window.setTimeout(() => {
outOfTime = true;
timeoutHandler();
}, 10000);
myProm.then(
(...args) => {
if (!outOfTime) {
window.clearTimeout(timeoutId);
suc(...args);
}
},
(...args) => {
if (!outOfTime) {
window.clearTimeout(timeoutId);
err(...args);
}
}
);
}).then(onSuccess, onError);
However, in case of a timeout, my newly defined promise will be forever-pending. Could this have any negative side effects? For example, the runtime not being able to clean up the Promise object because it's still pending (or something along those lines).
A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.
Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events.
A promise represents a single asynchronous operation that hasn't been completed yet, but is expected in the future. The promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
You don't need the Promise. resolve(result) at all. You just need a return value such as return result . If there's no return value from a .
There should be no side effect. It would be a browser bug if a non-referenced Promise
in whatever state is keeping resources.
Just make sure you don't keep any reference to the Promise
object and you'll be fine.
Beware that certain APIs such as setTimeout
will keep a reference to the closure up to the timeout value. This means that if you have a long timeout, like the 10s one, you should clear it as soon as you don't need it anymore. Otherwise your code can call thousands of setTimeout
within 10s, and each of them will keep a reference to the closure, which in your case will reference the Promise
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With