Preface
I recently encountered a problem in the project. When sending the same request in succession, if the second request is faster than the first request, then the data that is actually displayed is the first request, which will cause the problem that the data is inconsistent with the content I selected. Solution: When sending a request in the future, determine whether the previous request has been completed (the same interface), and cancel immediately if it is not completed. Then send a new request.
Introduction to Axios
Axios is a promise-based HTTP library that can be used in browsers and .
Axios uses cancel token to cancel request
Axios' cancel token API is based on cancelable promises proposals, which is still in its first phase.
You can use the factory method to create a cancel token, like this:
var CancelToken = ; var source = (); ('/user/12345', { cancelToken: }).catch(function(thrown) { if ((thrown)) { ('Request canceled', ); } else { // Handle errors } }); // Cancel the request (message parameter is optional)('Operation canceled by the user.');
2. You can also create a cancel token by passing an executor function to the constructor of the CancelToken:
var CancelToken = ; var cancel; ('/user/12345', { cancelToken: new CancelToken(function executor(c) { // The executor function receives a cancel function as a parameter cancel = c; }) }); // Cancel requestcancel();
I use the second solution in the project myself:
Extract all APIs for encapsulation:
import request from '../utils/request' // Configured Axios objectimport axios from 'axios' export function getLatenessDetailSize(params, that) { return request({ url: '/api/v1/behaviour/latenessDetailSize', method: 'post', params: params, cancelToken: new (function executor(c) { // Set cancel token = c; }) }) } export xxx
Specific business components:
import { getLatenessDetail } from "../api"; export default { data() { return { tableData: [], total: 0, page: 1, loadTable: false, params: { }, source: null } }, methods: { cancelQuest() { if (typeof === 'function') { ('Terminate request'); //Cancel request } }, getTableData(val) { () // Call before sending the request = val = true getLatenessDetail(, (val - 1) * 10, this) .then( res => { = false = } ) } }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.