An example of how to implement AbortController in a function which returns Promise.
/* this function would return a Promise | |
* which would resolve with value `hello` | |
* after 4s | |
*/ | |
function abortTask({ signal }) { | |
return new Promise((resolve, reject) => { | |
// 1. check if it's already aborted | |
if (signal && signal.aborted) { | |
return reject(new DOMException('`signal` is in `aborted` state', 'ABORT_ERR')); | |
} | |
// wait for 4s | |
setTimeout(() => resolve("hello"), 4000); | |
// 2. add a listener to `signal` to check its state | |
signal && signal.addEventListener('abort', () => { | |
// reject promise when signal.aborted changes to `true` | |
return reject(new DOMException('aborted by user', 'ABORT_ERR')); | |
}) | |
}) | |
} | |
/* DRIVER CODE */ | |
let signal; // just so that I could re-use it | |
// when `signal.aborted` is `false` | |
const abortController_1 = new AbortController(); | |
signal = abortController_1.signal; | |
abortTask({ signal }) | |
.then(t => console.log(t)) // hello | |
.catch(e => console.error(e.message)) | |
// when `signal.aborted` is `true` | |
const abortController_2 = new AbortController(); | |
signal = abortController_2.signal; | |
abortController_2.abort(); | |
abortTask({ signal }) | |
.then(t => console.log(t)) | |
.catch(e => console.error(e.message)) // err | |
// when user calls AbortController.abort() | |
const abortController_3 = new AbortController(); | |
signal = abortController_3.signal; | |
// abort task in 2s | |
setTimeout(() => abortController_3.abort(), 2000); | |
abortTask({ signal }) | |
.then(t => console.log(t)) | |
.catch(e => console.error(e.message)) // err |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment