前言:
在項目中經常有一些場景會連續發送多個請求,而異步會導致最后得到展示的結果可能不是最后一次發送請求返回的結果,且對性能也有非常大的影響。
場景:
列表式切換商品,有時候上一次請求的結果非常慢,而我又點了另外一個商品,這時候第二次請求的接口比上一次快,那么就點擊第二次的商品看到的信息卻是上一次的商品信息,這樣的用戶體驗極其不好;
解決方案:
在點擊下一個商品的時候,將上一個商品請求的接口中斷取消請求。
代碼如下:
import axios from 'axios'
export default {
data() {
return {
source: null,
}
},
methods: {
cancelRequest() {
if (typeof this.source === 'function') {
this.source()
}
},
getProductPackageInfo() {
const _this = this;
this.cancelRequest();
// 取消上一次請求
axios({
method: 'post',
url: this.secondURL.getProductPackageInfo,
data: { name: '小白' },
cancelToken: new axios.CancelToken((c) => {
_this.source = c
}),
})
.then((res) => {
// 返回數據進行操作
}).catch((err) => {if (axios.isCancel(err)) {
console.log('Rquest canceled', err.message);
//請求如果被取消,這里是返回取消的message
} else {
console.log(err);
}
})
},