how to cancel/abort ajax request in axios

前端 未结 8 682
广开言路
广开言路 2020-12-05 06:19

I use axios for ajax requests and reactJS + flux for render UI. In my app there is third side timeline (reactJS component). Timeline c

8条回答
  •  失恋的感觉
    2020-12-05 06:38

    Typically you want to cancel the previous ajax request and ignore it's coming response, only when a new ajax request of that instance is started, for this purpose, do the following:

    Example: getting some comments from API:

    // declare an ajax request's cancelToken (globally)
    let ajaxRequest = null; 
    
    function getComments() {
    
        // cancel  previous ajax if exists
        if (ajaxRequest ) {
            ajaxRequest.cancel(); 
        }
    
        // creates a new token for upcomming ajax (overwrite the previous one)
        ajaxRequest = axios.CancelToken.source();  
    
        return axios.get('/api/get-comments', { cancelToken: ajaxRequest.token }).then((response) => {
            console.log(response.data)
        }).catch(function(err) {
            if (axios.isCancel(err)) {
               console.log('Previous request canceled, new request is send', err.message);
            } else {
                   // handle error
            }
        });
    }
    

提交回复
热议问题