Skip to content

Instantly share code, notes, and snippets.

@ebidel ebidel/abort.js
Created Sep 27, 2018

Embed
What would you like to do?
Aborting Promises/fetch
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Abort promises</title>
</head>
<body>
<button class="download">download</button>
<button class="abort">abort</button>
<script>
let controller = new AbortController();
async function fetchJson() {
const url = 'https://www.chromestatus.com/features.json';
// Aborting a fetch();
const resp = await fetch(url, {signal: controller.signal});
const json = await resp.json();
console.log(json);
return json;
}
async function longPromise() {
return new Promise((resolve, reject) => {
// Aborting a Promise.
controller.signal.addEventListener('abort', () => {
window.clearTimeout(timeout);
reject(new DOMException('Aborted', 'AbortError'));
});
const timeout = setTimeout(() => {
console.log('longPromise done');
resolve();
}, 3000);
});
}
const downloadBtn = document.querySelector('.download');
downloadBtn.addEventListener('click', longPromise);
downloadBtn.addEventListener('click', fetchJson);
const abortBtn = document.querySelector('.abort');
abortBtn.addEventListener('click', (e) => {
controller.signal.addEventListener('abort', () => {
controller = new AbortController(); // allows to hit download button again.
});
controller.abort();
console.log('Aborted');
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.