axios 个人使用习惯分享

提起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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值