1、通過AbortController
這是官方標(biāo)準(zhǔn)手段,真正意義的阻止請求(不支持ie)
后端接口設(shè)置的兩秒返回數(shù)據(jù)
function myFetch() {
const controller = new AbortController();
const signal = controller.signal;
fetch('http://localhost:3000/aaa/bbb', {
method: 'post',
signal,
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json()).then(res => {
console.log(res);
return res;
}).catch(e => {
console.log(e);
})
// setTimeout(()=> {
// controller.abort();
// }, 1000)
}
默認(rèn)結(jié)果:
解開定時器后:
2、模擬中斷
通過promise,成功用resolve返回,失敗用reject返回(瀏覽器上,請求依然會發(fā)出,并得到響應(yīng))
第一種方法:文章來源:http://www.zghlxwxcb.cn/news/detail-657357.html
function getData() {
return new Promise((resolve, reject) => {
myFetch().then(res => {
resolve(res);
});
setTimeout(() => {
reject({
code: '500',
msg: '請求失敗'
})
}, 1000);
})
}
async function gotData() {
try {
const data = await getData();
console.log(data);
} catch (error) {
console.log(error);
}
}
gotData();
運行結(jié)果:
第二種方法:文章來源地址http://www.zghlxwxcb.cn/news/detail-657357.html
function getData() {
let myReject = null;
let myPromise = new Promise((resolve, reject) => {
myReject = reject;
myFetch().then(res => {
resolve(res);
});
});
myPromise.abort = () => myReject({
code: '500',
msg: '請求失敗'
});
return myPromise;
}
async function gotData() {
const result = getData();
result.then(res => {
console.log(res);
}).catch(e => {
console.log(e);
})
setTimeout(() => {
result.abort();
}, 1000);
}
gotData();
到了這里,關(guān)于js fetch請求中斷的幾種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!