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).