Created
September 25, 2019 09:09
-
-
Save ChaosPower/f5a525f959ae3c902ab6380b71cf3510 to your computer and use it in GitHub Desktop.
Javascript: Cancel Duplicate Axios calls.
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
let pending = []; // declares an array for storing the cancellation function and Axios identifier for each request | |
let cancelToken = axios.CancelToken; | |
let removePending = (config) => { | |
let xUrl = config.url.split('/'); | |
let yUrl = ''; | |
if(xUrl.length > 3) { | |
xUrl.pop(); // silently remove last Index; | |
yUrl = xUrl.join('/'); | |
} else { | |
yUrl = xUrl.join('/'); | |
} | |
for (let p in pending) { | |
if (pending [p].u === yUrl + '&' + config.method) {/// Execute the body of the function when the current request exists in the array | |
pending [p].f(); // perform cancellation | |
pending.splice(p, 1); | |
} | |
} | |
} | |
// HTTP request interceptor | |
axios.interceptors.request.use(config => { | |
removePending(config); // Execute a cancel operation before sending an Axios | |
config.cancelToken = new cancelToken((c) => { | |
let xUrl = config.url.split('/'); | |
let yUrl = ''; | |
if(xUrl.length > 3) { | |
xUrl.pop(); // silently remove last Index; | |
yUrl = xUrl.join('/'); | |
} else { | |
yUrl = xUrl.join('/'); | |
} | |
console.log(yUrl); | |
// Here, Axios identifies a string that I spliced using the request address-request method, although you can choose some other ways. | |
pending.push({u: yUrl + '&' + config.method, f: c}); | |
}); | |
return Promise.resolve(config) | |
}, error => { | |
return Promise.reject(error) | |
}); | |
// HTTP response interceptor | |
axios.interceptors.response.use(data => { | |
removePending(data.config); // After an Axios response, perform a cancel operation to remove completed requests from pending | |
return Promise.resolve(data) | |
}, error => { | |
// Load failure | |
// return {'data': {status: 'cancelled'}} | |
return Promise.reject(error) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment