background

Recently, the company carried out the development and upgrade of version 2.0 of the business system. In the process of development, there was a scene like this: For IP verification If IP verification is by showing some of the content, on the contrary don’t display a message, see this a lot of people will say that is very simple Direct request control just a matter of, don’t worry what’s more, for the request of the IP authentication, no more than 30 s IP to verify the interface and then someone says add timeout is very simple, that’s right is to add a timeout, And then there’s a problem with the request not being removed after the timeout is added and when you click again, the last request that was returned has a result and the control of the page is determined by the data from the last request rather than the data from our current request and that’s a problem. (Bosses are known to cancel requests here)

Cancellation and timeout handling of native JS requests

let xhr =  new XMLHTTPRequest()
xhr.open('get',url)
xhr.onreadystatechange=function(){
if(xhr.readyState! =4)return
if(xhr.status===200) {/ / success
}else{
/ / fail}}/ / timeout
xhr.timeout=3000
xhr.ontimeout=function(){
// The request was cancelled after the timeout
xhr.abort()
}
xhr.send()
Copy the code

Request cancellation and timeout processing for AXIos

const service= axios.create({
baseURL:"".// Base address
timeout:""// The timeout period
})
const cancelToken=axios.CancelToken //
let cancel // Request variables
let promiseArr={} // Cancel the requested array of functions
service({
method:"Request method".data: {}// Post requests data
param: {}//get request parameters
url / / address
cancelToken:new Canceltoken(c= >{
//c is the requested cancellation function
cancel=c
})
})
// Request interception

service.interceptors.request.use(config= >{
if(promise[config.url]){
  promise[config.url]('Function cancelled')  // Cancel the previous request
  promise[config.url]=cancel
}else{
// Add to the map of the cancel function
  promise[config.url]=cancel

}
})
// When used
  promise[config.url]('Function cancelled')
// If the timeout for a single request is inconsistent with the global timeout, we can use the promise and request cancellation functions

new Promise((resolve,reject) = >{
this.$get(url).then(res= >{
// Normal request
resolve(res)
})

setTimeout(() = >{
// Reject the request after the timeoutPromiseArr [url](' request to cancel ')},3000)})Copy the code

Fatch requests cancel and time out

new Promise((resolve,reject) = >{
const controller = new AbortController();
const { signal } = controller;
new Promise((resolve,reject) = >{
fetch("http://localhost:8000", { signal }).then(response= > {
    resolve(response)
}).catch(e= > {
   reject('Request failed')});setTimeout(() = >{
// Reject the request after the timeout
 controller.abort();
 reject('timeout')},3000)})Copy the code