AbortController can be used to abort one or more web requests.
Basic Usage#
// Create an instance of AbortController
const controller = new AbortController()
const signal = controller.signal
// Listen for the abort event and execute the callback to print after controller.abort() is called
signal.addEventListener('abort', () => {
console.log(signal.aborted) // true
})
// Trigger the abort
controller.abort()
Demo#
fetch accepts AbortSignal
as part of the second parameter:
const controller = new AbortController()
const signal = controller.signal
fetch('https://slowmo.glitch.me/5000', { signal })
.then((r) => r.json())
.then((response) => console.log(response))
.catch((err) => {
if (err.name === 'AbortError') {
console.log('Fetch was aborted')
} else {
console.log('Error', err)
}
})
// Abort the request after 2s, triggering 'AbortError'
setTimeout(() => controller.abort(), 2000)
Using in axios#
const controller = new AbortController()
axios
.get('/foo/bar', {
signal: controller.signal,
})
.then(function (response) {
//...
})
// Cancel the current request
controller.abort()