学习代码示例
import axios from axios;
const MAX_RETRY = 3; // 重试次数
const RETRY_INTERVAL = 500; // 重试时间间隔
const TIMEOUT = 15 * 1000; // 超时时间
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function request(url, method, params, retry = MAX_RETRY, hookResult = null) {
let res;
let requireRetry;
try {
let config = {
url: url,
method: method,
timeout: TIMEOUT
}
if (Object.is(method, 'get')) {
config['params'] = params;
} else if (Object.is(method, 'post')) {
config['data'] = params;
}
res = await axios.request(config);
// 发生服务器错误,重试
if (res && res.status >= 500) requireRetry = true;
// 使用调用者逻辑判断,如果未达到预期,重试
if (hookResult && !hookResult(res)) requireRetry = true;
} catch(err) {
console.log(err);
// 发生网络错误,重试
requireRetry = true;
if (requireRetry && retry > 0) {
await sleep(TIMEOUT)
console.log('重试', retry)
res = await request(url, method, params, --retry)
}
}
return res
}
function get(url, params = {}, retry = MAX_RETRY, hookResult = null) {
return request(url, 'get', params, retry, hookResult)
}
function post(url, data = {}, retry = MAX_RETRY, hookResult = null) {
return request(url, 'post', data, retry, hookResult)
}
export default {
request,
get,
post
}
这里用到一个之前没用过的 Object.is 函数,它和 === 有什么区别呢。查阅 MDN 文档,直接看 Polyfill 实现,相信你就明白啦
if (!Object.is) {
Object.is = function(x, y) {
// SameValue algorithm
if (x === y) { // Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
};
}
本质使用的还是严格比较运算符,看注释也了解到,不同之处只有两个
- +0不等于-0
- NaN等于自身