Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Created May 20, 2019 15:18
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 daliborgogic/16fe92835245bd9fea460e1af32562d4 to your computer and use it in GitHub Desktop.
Save daliborgogic/16fe92835245bd9fea460e1af32562d4 to your computer and use it in GitHub Desktop.
Abortable Fetch
// 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
})
@daliborgogic
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment