Created
September 27, 2018 18:17
-
-
Save ebidel/0830d271ab804aff3b0376575e68846c to your computer and use it in GitHub Desktop.
Aborting Promises/fetch
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
<!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