Skip to content

Instantly share code, notes, and snippets.

@MrChocolatine
Last active November 11, 2021 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrChocolatine/174248e2092c5fa46bacb4069b3dc327 to your computer and use it in GitHub Desktop.
Save MrChocolatine/174248e2092c5fa46bacb4069b3dc327 to your computer and use it in GitHub Desktop.
Abort Promises running in parallel
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