最常见用法:
const fn = async()=>{const temp = await makePromise()return temp +1}
好处
完全没有缩进,就像是在写同步代码
封装一个async函数
async function 摇色子(){return Math.floor(Math.random()*6)+1}
如果需要reject,直接throw Erroe(‘xxx’),然后错误的话需要try,catch去捕获
const a1 = function(){throw new Error(`色子坏了`)}const fn = async()=>{try{const result = await a1()console.log(result)} catch(e){console.log(e)}}fn()

await错误处理
常见的处理
let responsetry{response = await axios.get('/xxx')} catch(e){if(e.response){console.log(e.response.states)throw e}}console.log(response)
简洁推荐的写法:
const response = await axios.get('/xxx').catch(errorHandler)console.log(response)
then和await结合使用。
这样写的细节:
- 可以把4xx/5xx等常见错误用拦截器全局处理
- await只关心成功,失败全部交给errorHandler
- errorHandler也可以放在拦截器里
await的传染性
console.log(1)await console.log(2)console.log(3)
这样写的话,console.log(3)就变成了异步任务了。
因为await的传染性,写在await之后的代码都会变成异步
如果想要立即执行代码,就把代码放在await前面就好了。
