1.GitHub搜索项目
2.优雅处理async await 中处理异常
方法一:try...catch
const getStudent = async () =>{
try {
const inf = await axios.get('http://localhost:3000/api1/students')
console.log('inf',inf.data);
} catch (error) {
console.log('error',error);
}
}
这是较为常见的用法,但还是稍稍显的没那么优雅
方法二:使用await-to-js库
npm await-to-js --save
import to from 'await-to-js'
const getStudent = async () =>{
const [err,inf] = await to(axios.get('http://localhost:3000/api1/students'))
if(err){
console.log('err',err);
return
}
console.log('inf',inf);
}
简单解释一下,to方法可传入一个promise对象,并且返回值是一个数组,数组的第一个元素用于接受rejected后返回的参数,第二个元素用于接收resolved后返回的参数,若数组的第一个元素不为空,则表明被rejected,综上,便可优雅的处理async/await的异常了。
3.axios封装处理异常
export function request(config) {
const instance = axios.create({
baseURL: 'http://' + urlConfig + ':' + host,
timeout: 150000
})
// 请求拦截
instance.interceptors.request.use(config => {
return config
},error => {
Message(error.message)
return Promise.reject(err)
})
// 响应拦截
instance.interceptors.response.use(response => {
if (response.data.code !== 1) {
Message(response.data.msg)
}
return response.data
}, error => {
Message(error.message)
return Promise.reject(err)
})
return instance(config)
}
4.import * as obj from ‘xx’ 这种写法是把所有的输出包裹到obj对象里
5.开发过程中使用,可以早点下班的coding小技巧