Created
December 10, 2019 13:39
-
-
Save reducio/003887da7dc492aec007a9bf088dacf6 to your computer and use it in GitHub Desktop.
How to cancel fetch request?
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
(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