实现效果
规定时间内如果网络请求还未完成,则自动取消请求,并报错请求超时。
重点
使用setTimeout设置超时时间。
使用Promise.race()
方法实现效果。
// 超时方法
function defineTimeout(time) {
return new Promise((resolve,reject) => {
setTimeout(() => {
reject("请求超时!");
cancelXhr(); // 如果本方法比myRequest方法先执行完,则终止网络请求。
}, time);
});
}
// 网络请求方法
function myRequest(config) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(config.method, config.url);
xhr.send();
// 取消网络请求
cancelXhr = () => {
xhr.abort();
}
xhr.onload = () => {
resolve(xhr.responseText);
}
xhr.onerror = () => {
reject(xhr.statusText);
}
})
}
// 整合方法,并比较速度
function myajax(config, time) {
return Promise.race([myRequest(config), defineTimeout(time)]).then(res => {
console.log('请求成功!' + res);
}).catch(err => {
console.log('请求失败!' + err);
})
}
// 使用
let config = {
method: "GET/POST等",
url: "接口地址"
}
myajax(config, 2000);