問題的來源
用el-autocomplete遠(yuǎn)程獲取數(shù)據(jù)時(shí),點(diǎn)擊輸入框會(huì)觸發(fā)第一次請(qǐng)求,然后輸入搜索文字后會(huì)觸發(fā)第二次請(qǐng)求,兩次請(qǐng)求間隔較短,有時(shí)候會(huì)出現(xiàn)第二次請(qǐng)求比第一次請(qǐng)求先返回的情況,導(dǎo)致我們期望的第二次發(fā)送的請(qǐng)求返回的數(shù)據(jù)會(huì)被第一次請(qǐng)求返回的數(shù)據(jù)覆蓋掉
解決思路
在發(fā)送第二次請(qǐng)求的時(shí)候如果第一次請(qǐng)求還未返回,則取消第一次請(qǐng)求,以保證后發(fā)送的請(qǐng)求返回的數(shù)據(jù)不會(huì)被先發(fā)送的請(qǐng)求覆蓋。
axios官方文檔取消請(qǐng)求說明
方法一:
const CancelToken = axios.CancelToken;const source = CancelToken.source();axios.get('/user/12345', { 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: source.token})// cancel the request (the message parameter is optional)source.cancel('Operation canceled by the user.');方法二:
const CancelToken = axios.CancelToken;let cancel;axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; })});// cancel the requestcancel();不可行方案
注:本例采用的的axios的實(shí)例發(fā)送請(qǐng)求,其他情況未測(cè)試
初始方案A
請(qǐng)求時(shí)的代碼如下:
/* 接口listApi.getList方法如下 */const CancelToken = axios.CancelTokenconst source = CancelToken.source()getVideoList ({ key}) { return axiosInstance.post('/video/list', { key }, { cancelToken: source.token })},cancelRequest () { // 取消請(qǐng)求 source.cancel()}/* 頁面中獲取列表的函數(shù) */getList (query, cb) { // 取消之前的請(qǐng)求 listApi.cancelRequest() // 發(fā)送請(qǐng)求 listApi.getVideoList({key: 'value'}).then(resp => { // handle response data }).catch(err => { if (axios.isCancel(err)) { console.log('Request canceled!') } else { this.$message.error(err.message) } })}此時(shí)chrome的Network面板并未發(fā)送getVideoList請(qǐng)求,控制臺(tái)輸出Request canceled!
原因猜想如下:
執(zhí)行l(wèi)istApi.cancelRequest()時(shí)會(huì)將listApi.getVideoList({key: 'value'})返回的Promise狀態(tài)置為reject,因此在執(zhí)行l(wèi)istApi.getVideoList({key: 'value'})時(shí)并未發(fā)送請(qǐng)求,而直接執(zhí)行catch塊中的代碼,在控制臺(tái)輸出Request canceled!。
改進(jìn)方案B
將getList方案改造如下:
/* 頁面中獲取列表的函數(shù) */getList (query, cb) { // 發(fā)送請(qǐng)求 listApi.getVideoList({key: 'value'}).then(resp => { // handle response data // 取消請(qǐng)求 listApi.cancelRequest() }).catch(err => { if (axios.isCancel(err)) { console.log('Request canceled!') } else { this.$message.error(err.message) } })}
新聞熱點(diǎn)
疑難解答
圖片精選