Last active
November 11, 2021 18:10
-
-
Save MrChocolatine/174248e2092c5fa46bacb4069b3dc327 to your computer and use it in GitHub Desktop.
Abort Promises running in parallel
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
const controller = new AbortController(); | |
const signal = controller.signal; | |
let RESOLVED_P; | |
function doSomethingAsync(pIndex, pDelay) { | |
if (signal.aborted) { | |
return Promise.reject(new DOMException('Aborted', 'AbortError')); | |
} | |
return new Promise((resolve, reject) => { | |
console.log('Start Promise', pDelay); | |
const timeout = window.setTimeout(resolve, pDelay, | |
pDelay === 6000 ? { short: true } : undefined | |
); | |
signal.addEventListener('abort', () => { | |
if (RESOLVED_P !== undefined && pIndex !== RESOLVED_P) { | |
window.clearTimeout(timeout); | |
reject(new DOMException('Abort promise ' + pDelay, 'AbortError')); | |
console.log('Abort promise', pDelay); | |
} | |
}); | |
}); | |
} | |
function process_p(index, result) { | |
console.log(`process_p | #${index} has resolved`); | |
if (result?.short === true) { | |
RESOLVED_P = index; | |
controller.abort(); | |
} | |
} | |
function main() { | |
;[ 3000, 6000, 10000, 11000 ].forEach((delay, index) => { | |
doSomethingAsync(index, delay) | |
.then((result) => process_p(index, result)) | |
.catch(() => { /* console.log(`p #${index} rejected`, p) */ }); | |
}); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment