Created
May 20, 2019 15:18
-
-
Save daliborgogic/16fe92835245bd9fea460e1af32562d4 to your computer and use it in GitHub Desktop.
Abortable Fetch
This file contains hidden or 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
// This will allow us to abort the fetch | |
let controller | |
// Abort if the user clicks | |
abortBtn.addEventListener('click', () => | |
if (controller) controller.abort() | |
) | |
// Load the content | |
loadBtn.addEventListener('click', async () => { | |
controller = new AbortController() | |
const signal = controller.signal | |
// Prevent another click until this fetch is done | |
loadBtn.disabled = true | |
abortBtn.disabled = false | |
try { | |
const contentUrl = 'https://example.com/api' | |
// Fetch the content & use the signal for aborting | |
const response = await fetch(contentUrl, { signal }) | |
// Add the content to the page | |
output.innerHTML = await response.json() | |
} catch (error) { | |
// Avoid showing an error message if the fetch was aborted | |
if (error.name !== 'AbortError') { | |
output.textContent = 'Fetching failed.' | |
} | |
} | |
// These actions happen no matter how the fetch ends | |
loadBtn.disabled = false | |
abortBtn.disabled = true | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Aborting Fetch whatwg/fetch#27
API https://dom.spec.whatwg.org/#aborting-ongoing-activities