Skip to content

Instantly share code, notes, and snippets.

@ebidel
Created September 27, 2018 18:17
Show Gist options
  • Save ebidel/0830d271ab804aff3b0376575e68846c to your computer and use it in GitHub Desktop.
Save ebidel/0830d271ab804aff3b0376575e68846c to your computer and use it in GitHub Desktop.
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