vue中简单使用async和await

前言:

      async就是将函数返回值使用Promise.resolve()包裹了下,和then中处理返回值一样,并且await只能配套async使用, 这两个名词也不是很陌生了,网上的资料一大把,这里简单说个使用场景和使用案例

场景:

     我现在需要在执行其他方法之前,先请求后台获取数据,这里我不想用函数嵌套了,就可以用这个方法

具体操作:

1、先定义函数

 async toReadCard(tit) {
                let card_no = '';
                await useCode().then(res=>{
                    if(tit=='add'){
                        this.account.owner.cardID = res.data.card_no;//卡号
                        this.account.owner.bl_card = '00'+this.account.owner.employeeID//卡号展示内容
                    }
                    card_no =  res.data.card_no;
                }).catch(error=>{
                    this.$Message.error('请先放置卡片!');
                })
                return card_no;
            },

   2、在外界调用这个函数

let  aaa = this.toReadCard();

3、得到的结果并不是  ‘’  而是我们后台传来的card_no

结论:

这个方法简单来说跟函数二次嵌套,在获取完第一个后台中调用第二个后台是一样的呈现效果

    

猜你喜欢

转载自blog.csdn.net/qq_41619796/article/details/107717862