最常见用法:

  1. const fn = async()=>{
  2. const temp = await makePromise()
  3. return temp +1
  4. }

好处
完全没有缩进,就像是在写同步代码

封装一个async函数

  1. async function 摇色子(){
  2. return Math.floor(Math.random()*6)+1
  3. }

如果需要reject,直接throw Erroe(‘xxx’),然后错误的话需要try,catch去捕获

  1. const a1 = function(){
  2. throw new Error(`色子坏了`)
  3. }
  4. const fn = async()=>{
  5. try{
  6. const result = await a1()
  7. console.log(result)
  8. } catch(e){
  9. console.log(e)
  10. }
  11. }
  12. fn()

image.png

await错误处理

常见的处理

  1. let response
  2. try{
  3. response = await axios.get('/xxx')
  4. } catch(e){
  5. if(e.response){
  6. console.log(e.response.states)
  7. throw e
  8. }
  9. }
  10. console.log(response)

简洁推荐的写法:

  1. const response = await axios.get('/xxx').catch(errorHandler)
  2. console.log(response)

then和await结合使用。

这样写的细节:

  • 可以把4xx/5xx等常见错误用拦截器全局处理
  • await只关心成功,失败全部交给errorHandler
  • errorHandler也可以放在拦截器里

await的传染性

  1. console.log(1)
  2. await console.log(2)
  3. console.log(3)

这样写的话,console.log(3)就变成了异步任务了。
因为await的传染性,写在await之后的代码都会变成异步
如果想要立即执行代码,就把代码放在await前面就好了。