大家知道axios是一个promise,相对于传统的回调函数使用起来已经比较方便了,但是我想是否可以更进一步,使用async await来让我们的心智消耗更少呢?
虽然使用await可以直接调用promise,就像下面这样
async getWithAxios() {
let info = await getInfo();
console.log(info)
}
getWithAxios();
但是有一个问题,promise的reject需要使用try catch捕获,众所周知try catch是非常浪费性能的,因此我把axios的request再次包装了一层。
const service = axios.create({....});
const request = async (...args) => {
return await service(...args).then(res => {
return res;
}).catch(res => {
return res;
});
}
export default request;
这样的话,我们在调用接口时更简单了,只需要关心返回结果即可