Skip to content

Instantly share code, notes, and snippets.

@reducio
Created December 10, 2019 13:39
Show Gist options
  • Save reducio/003887da7dc492aec007a9bf088dacf6 to your computer and use it in GitHub Desktop.
Save reducio/003887da7dc492aec007a9bf088dacf6 to your computer and use it in GitHub Desktop.
How to cancel fetch request?
(function() {
const log = (msg) => console.log(msg)
const options = {
controller: undefined,
signal: undefined,
approveMaxTime: 2000,
url: 'https://jsonplaceholder.typicode.com/photos',
controller() {
this.controller = new AbortController()
},
signal() {
this.signal = this.controller.signal
},
abort() {
this.controller.abort()
},
}
const request = () => {
options.controller()
options.signal()
return fetch(options.url, options)
.then(response => {
clearTimeout(timeoutID)
return response.json()
})
.then(json => log(json))
}
const limit = new Promise((reject) => {
timeoutID = setTimeout(() => {
reject(
options.abort(),
log('timeout, request aborted!')
)
}, options.approveMaxTime)
})
const timeoutRequest = () => {
return Promise.race([request(), limit])
.catch(reason => log(reason))
}
timeoutRequest()
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment