国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

axios取消請(qǐng)求的實(shí)踐記錄分享

2024-05-06 15:29:27
字體:
供稿:網(wǎng)友

問題的來源

用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) } })}            
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 武鸣县| 广西| 湖州市| 岳普湖县| 万源市| 周宁县| 蕲春县| 乐平市| 萍乡市| 大荔县| 绥芬河市| 喜德县| 安溪县| 漳州市| 呼和浩特市| 望都县| 大港区| 洛川县| 丹棱县| 顺昌县| 乌苏市| 甘谷县| 钟祥市| 通山县| 南通市| 荥经县| 江川县| 桓台县| 修武县| 宝鸡市| 乌兰察布市| 宽城| 沧源| 宿州市| 晋江市| 阳原县| 鄂托克旗| 会东县| 广元市| 平罗县| 淳安县|