“This is the first day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021”
Demand for the premise
Anti-shake: During the development process, users only use the data generated in the last interaction during the rapid interaction, and then initiate a request, such as frequent TAB switching, or fast data input, or the need to cancel the operation during the export or download of a file. These need to be handled when or after the interface is requested to avoid some useless requests or differences in the order in which the interface returns.
If we do not process these outstanding requests, they can significantly affect the performance of the page and even cause subsequent requests to time out.
Lock state: When no data is returned by the previous interface, the interaction is locked until the data is returned correctly or the interface times out.
Cancel previous request: To cancel a previous request before sending the next one.
In the first two ways, control is carried out before the request is made and no control is taken after the request is made. The last option is to cancel the interrupt request while it is still on the road, and then issue a new request regardless of the timing.
During the development of Vue, most HTTP requests were made using AXIos, so how do we abort an HTTP request in AXIos? Take a look at the axios website. Sure enough, Axios provided a CancelToken to cancel the initiated request.
Method of use
- Add properties of the configuration object;
- Declare global variables;
- Assign the value of C to cancel;
- Execute cancel request;
let cancel = null;
btn.onclick = function() {
axios({
methods: 'GET',
url: '',
cancelToken: new axios.CancelToken(function(c) {
cancel = c;
}).then(res => {
console.log(res)
})
})
}
Copy the code
Prevent multiple requests
Clicking on a send request increases server stress if the data has not been returned, so determine if the last request was completed.
Uncompleted ——– cancel previous request; Completion ——— returns data;
BTNS [0].onclick = function() {// Check whether the last request completed if(cancel! == null) {// Cancel the last request; } axios({ methods: 'GET', url: 'http://localhost:3000/posts', cancelToken: new axios.CancelToken(function(c) { cancel = c; }) }).then(res => { cancel = null; })},Copy the code