一、中断网络请求的原因
场景
1:用户取消了操作,此时不需要继续等待请求的响应。
2:页面进行了跳转,原来的请求已经不再需要。
1:网络请求超时,需要重试或取消。
如果不中断请求导致
1:浪费网络资源和服务器资源。
1:可能导致页面卡顿或性能下降。
1:用户体验不佳,如页面跳转后仍在等待旧请求的响应。
二、如何中断网络请求
1:XMLHttpRequest
对于XMLHttpRequest对象,我们可以使用abort()
方法来中断请求
var xhr = new XMLHttpRequest ( ) ;
xhr. open ( 'GET' , 'https://api.example.com/data' , true ) ;
xhr. onreadystatechange = function ( ) {
if ( xhr. readyState == 4 ) {
if ( xhr. status == 200 ) {
} else {
}
}
} ;
xhr. abort ( ) ;
2:Fetch API
对于Fetch API
,由于其返回的是一个Promise
对象,我们无法直接调用类似于abort()
的方法来中断请求。但我们可以使用一些技巧来实现类似的功能
一种常用的方法是使用AbortController
和AbortSignal
。AbortController
提供了一个signal
属性,该属性是一个AbortSignal
对象。我们可以将signal
对象作为参数传递给fetch
请求的options
对象。当需要中断请求时,我们可以调用AbortController
的abort()
方法
const controller = new AbortController ( ) ;
const signal = controller. signal;
fetch ( 'https://api.example.com/data' , { signal } )
. then ( response => {
if ( ! response. ok) {
throw new Error ( 'Network response was not ok' ) ;
}
return response. json ( ) ;
} )
. then ( data => {
} )
. catch ( error => {
if ( error. name === 'AbortError' ) {
} else {
}
} ) ;
controller. abort ( ) ;
3:axios
在使用axios进行网络请求时,中断请求的需求同样存在。axios提供了几种方法来优雅地中断正在进行的网络请求
1:使用CancelToken (v0.22.0之前)
const CancelToken = axios. CancelToken;
const source = CancelToken. source ( ) ;
axios. get ( '/user/12345' , {
cancelToken : source. token
} ) . catch ( function ( thrown ) {
if ( axios. isCancel ( thrown) ) {
console. log ( '请求被取消:' , thrown. message) ;
} else {
}
} ) ;
source. cancel ( '用户取消了请求' ) ;
2:使用构造函数形式
const CancelToken = axios. CancelToken;
let cancel;
axios. get ( '/user/12345' , {
cancelToken : new CancelToken ( function executor ( c ) {
cancel = c;
} )
} ) ;
cancel ( ) ;
3:AbortController
const controller = new AbortController ( ) ;
axios. get ( '/user/12345' , {
signal : controller. signal
} ) . then ( function ( response ) {
} ) . catch ( function ( error ) {
if ( error. name === 'AbortError' ) {
console. log ( '请求被中止' ) ;
} else {
}
} ) ;
controller. abort ( ) ;