Recently, I encountered a problem that if the second request is faster than the first one when sending the same request in succession, then the data of the first request is actually displayed, which will result in inconsistency between the data and the content I choose. Solution: When subsequent requests are sent, determine whether the previous request is completed (the same interface), and cancel it immediately if it is not completed. Then send a new request.
Axios introduction
Axios is a promise-based HTTP library that can be used in browsers and node.js.
Axios cancels requests using cancel token
Axios cancel token API is based on cancelable promises proposal, which is still in its first stage.
CancelToken.source factory method can be used to create cancel token, like this:
var CancelToken = axios.CancelToken; var source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // Handling errors } }); // Cancel requests (message parameters are optional) source.cancel('Operation canceled by the user.'); //Welcome to Jiaquan Stack Development Exchange Junyang: 864305860 Learning Exchange
2. You can also create cancel token by passing an executor function to the CancelToken constructor:
var CancelToken = axios.CancelToken; var cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // The executor function receives a cancel function as a parameter cancel = c; }) }); // Cancellation request cancel();
The second option:
Extract all APIs for encapsulation:
import request from '../utils/request' // Configured Axios objects import axios from 'axios' export function getLatenessDetailSize(params, that) { return request({ url: '/api/v1/behaviour/latenessDetailSize', method: 'post', params: params, cancelToken: new axios.CancelToken(function executor(c) { // Setting cancel token that.source = 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 this.source === 'function') { this.source('Termination request'); //Cancellation request } }, getTableData(val) { this.cancelQuest() // Call before request is sent this.page = val this.loadTable = true getLatenessDetail(this.params, (val - 1) * 10, this) .then( res => { this.loadTable = false this.tableData = res.data } ) } }