提起axios大家应该不陌生,如果有没用到过的可以先自行百度下。
其实使用起来很简单,但是真正在项目里而且还需要用的很舒服,就需要自己包装下。
先看下官方栗子
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
从上述代码 可以知道 axios.get() 或者 post() 返回的是promise 对象
一个两个结构还好如果多的话 then then then … 会很长。
主要看下最后一段代码,async await , await 可以接受 promise对象返回的数据
这种写法,必须要一个 try catch 去捕获 promise.reject()错误。
这里就想能让axios都是resolve就好了,实现其实很简单,需要自己处理下response拦截器。
想这样
// 响应拦截器
instance.interceptors.response.use(function (response) {
return response.data
}, function (error) {
return {code: 9, msg: error}
// return Promise.reject(error)
})
// 当然返回的错误格式需要你们根据实际情况定义。
这样的话后面就可以很舒服的去await了,也不需要trycatch,这个纯属个人习惯,至少在自己的业务里很爽,看看大家是不是有其它更好的方式
async function fetchData() {
let alls = await axios.all(P1,P2);
let result = await axios.get(url);
}