Last active
February 12, 2021 13:50
-
-
Save ccnokes/8dbd213192862b8671be58879e1cda86 to your computer and use it in GitHub Desktop.
Use AbortController to implement custom async task cancelling logic. Expounded upon here: https://cameronnokes.com/blog/cancelling-async-tasks-with-abortcontroller/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function wait(ms, opts = {}) { | |
return new Promise((resolve, reject) => { | |
let timerId = setTimeout(resolve, ms); | |
if (opts.signal) { | |
// implement aborting logic for our async operation | |
opts.signal.addEventListener('abort', event => { | |
clearTimeout(timerId); | |
reject(event); | |
}); | |
} | |
}); | |
} | |
let abortController = new AbortController(); | |
wait(100, { signal: abortController.signal }) | |
.then(() => console.log('wait complete')) | |
// catch the aborted promise rejection in here | |
.catch(console.error); | |
abortController.abort(); | |
// => Error: Event { type: 'abort', ... } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You don't clean up the event handler when
wait
returns normally (not aborted) which is a memory leak.