美文网首页
es6 async / await 使用经验总结

es6 async / await 使用经验总结

作者: 前端人 | 来源:发表于2020-07-03 17:53 被阅读0次

async await使用的注意事项

    1. async await注意 不能捕获Promise抛出的异常,所以我按下面的方法使用它

      async getPosterData(optType = 'search') {
          this.loading.table = true;
          let res = null;
          try {
              res = await api.getPosterData(param);
           } finally {
                    this.loading.table = false;
                    }
           }
      

也就是Promise进入catch函数时,如果这两不捕获这个异常,就会报错。

  • 2.async await必须成对在一个函数里使用,不能跨函数,如下是错误的

         async function test(){
                     [1,2,3].forEach( (item)=>{
                          await this.queryTable(item);//这个写法是错误的
                    })
        }
    

正确的应该是

             function test(){
                   [1,2,3].forEach( async (item)=>{
                        await this.queryTable(item);//这个写法才对
                  })
              }
  • 3.async await不能跨多个函数实现同步效果,只能在一个函数内部使用同步执行的效果

        async function getData() {
                  console.log(1)
                 useSystemMaAppId();//未加await不能按照1,2,3,4,5输出
                console.log(4)
                 await api.getPosterDetail({ id: this.id });
                console.log(5)
    
        }
         async function useSystemMaAppId() {
                console.log(2)
                 await api.getCustomPages()
               console.log(3)
    
           }
        //这样不能按顺序输出 1.2.3.4,5
       //把getData下面这个样子就可以同步输出
            async function getData() {
                  console.log(1)
                await useSystemMaAppId();//添加 await 这样可以按照 1,2,3,4,5的顺序输出
                console.log(4)
                 await api.getPosterDetail({ id: this.id });
                console.log(5)
    
        }
    
  • 4.async await标记的函数 返回值是一个pending状态的Promise,而且返回值会成为then回调的输入参数

          async function useSystemMaAppId() {
                console.log(2)
                 await api.getCustomPages()
               console.log(3)
             return 'test';
           }
     console.log(' 返回结果查看',   useSystemMaAppId());//打印后看到返回的是一个pending状态的Promise
     
             useSystemMaAppId().then(res=>{ console.log(res); })//打印出来的res为 test.
    

相关文章

网友评论

      本文标题:es6 async / await 使用经验总结

      本文链接:https://www.haomeiwen.com/subject/cjzsqktx.html