import qs from "qs"
import axios from "axios"
/**
* 顺序执行操作
* @param {*} arr 传递函数数组
*/
let _queue = async arr => {
let res = null
for (let promise of arr) {
try {
res = await promise(res)
} catch (error) {
return Promise.reject(error)
}
}
return res
}
// 无序执行
let _all = async params => await Promise.all(params)
const BASE_HOST = 'https://basehost'
let REQNUM = 0
let TIME_OUT = null
const errorHandle = (response) => {//错误处理
}
const instance = axios.create({
timeout: 1000 * 12,
baseURL: BASE_HOST
})
const setLoading = () => {
REQNUM--
clearTimeout(TIME_OUT)
if (!REQNUM) {
//关闭loading $loading({ show: false })
}
}
instance.interceptors.request.use(
config => {
config.beginTime = Date.now()
const token = getCookie()
token && (config.headers.Authorization = `Bearer ${token}`)
REQNUM++
if (+REQNUM === 1) {
TIME_OUT = setTimeout(() => {
$loading()
}, 500)
}
return config
},
error => Promise.error(error)
)
const _reject = response => {
//前端监控处理
errorHandle(response)
return Promise.reject(response)
}
instance.interceptors.response.use(
res => {
setLoading()
if (res.status === 200 && res.data.status_code === 200) {//请求成功
} else Promise.reject(res)
},
({ response }) => {
setLoading()
if (response) return _reject(response)
}
)
const post = (url, params = {}) => {
return instance({
method: "post",
url,
data:
Object.prototype.toString.call(params) === "[object FormData]" ? params : qs.stringify(params)
})
}
const get = (url, params = {}) => {
return instance({
method: "get",
url,
params
})
}
const [queue, all] = [_queue, _all].map(i => {
return async arr => {
let res = null
res = await i(arr)
return res
}
})
export { get, post, queue, all }