Vue uses axios to cancel the last request

Keywords: axios Vue

Project requirements: when switching goods in list mode, sometimes the result of the last request is very slow, and I click another product, at this time, the interface of the second request is faster than the last one, so the information you click the second product is the last product information, which is extremely bad user experience
Solution: when clicking the next product, interrupt the interface of the previous product request to cancel the request.  
The axios official website gives the method to cancel the request:

Method 1:
axios.get('/user/12345', {
  cancelToken: axios.CancelToken.source().token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: axios.CancelToken.source().token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
  •  
Method two:
let cancel;
axios.get('/user/12345', {
  cancelToken: new axios.CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

According to the requirements of the project, the solution is given:

vue: 
data(){
    return{
        source: null, //Save the cancellation request method
    }
},
methods:{
    cancelQuest(){
        if(typeof this.source ==='function'){
            this.source('Termination request'); //Cancellation request
        }
    },
    getInfo(id){
        const _this = this;
        this.cancelQuest(); //Cancel the last unfinished request before the request is sent;
        //Send request
        this.axios.get(`/markets/tradeInfo/${id}?top=40`,{
            cancelToken: new this.axios.CancelToken(function executor(c) {
            _this.source = c;
          })
        }).then(res =>{
            //handle result
        }).catch(error => {
            if (this.axios.isCancel(err)) {
                console.log('Rquest canceled', err.message); //If the request is cancelled, here is the message to return the cancellation
            } else {
                //handle error
                console.log(err);
            }
        })
    }
}

After this processing, when users click fast, the product information they see is the last product they click on; if necessary, it can be encapsulated in axios business methods.

Posted by PHPNewbie55 on Tue, 31 Dec 2019 20:17:42 -0800