1、通过AbortController
这是官方标准手段,真正意义的阻止请求(不支持ie)
后端接口设置的两秒返回数据
js
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)
}
默认结果:
解开定时器后:
2、模拟中断
通过promise,成功用resolve返回,失败用reject返回(浏览器上,请求依然会发出,并得到响应)
第一种方法:
js
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();
运行结果:
第二种方法:
js
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();