‘Cancel’ async Functions in JavaScript Using Promises
1 min readSep 19, 2020
JavaScript doesn’t provide a way to cancel long-running background tasks. However, it is possible to simulate this feature using Promises.
First, create a Promise. Inside the Promise’s constructor callback:
- Start a timer
- When the timer expires, call reject()
- Execute the function. When the returned Promise resolves:
- Stop the timer
- Call resolve() or reject()
Of course, there’s a problem: after the timeout, the function keeps executing. In order to stop the task after the timeout expires, you will need to devise your own solution. The easiest solution is for the task to poll a flag that would be set in step 2.
await new Promise((resolve, reject) => {
let timeout = setTimeout(() => {
timeout = undefined;
reject(new Error('Timeout'));
}, 5000 /* 5 seconds */);
realFunction().then(
(value) => {
if (timeout) {
clearTimeout(timeout);
resolve(value);
} else {
// realFunction finished after 5 seconds
}
},
(error) => {
if (timeout) {
clearTimeout(timeout);
reject(error);
} else {
// realFunction threw an exception after 5 seconds
console.error(error);
}
});
});