想要实现按顺序执行函数,使用async和await却报错?


async getNextFlow(){
                getNext(this.$store.state.productId,this.$store.state.current,'#').then(res=>{
                    
                    this.$store.state.current=res.data.next.substr(1)
                    
                    if(res.data.isJumped===1){
                                                   uni.redirectTo({
                                                        url:res.data.name
                                             })
                    }else{
                        let atomServiceMethod=res.data.name
                        await atomServiceList[atomServiceMethod]()    
                        
                        this.getNextFlow()
                        
                    
                        
                    }
                })
            },

就是以上这段函数,想要先atomServiceList ,再重新调用本函数this.getNextFlow(),请问该如何处理?


async getNextFlow() {
  let res = await getNext(xxx);
  if (res) {
    ...
  } else {
    await atom...();
    this.get...();
  }
}

这里作用域混淆了,看下图理解一下

img

所以如果你要在 then 里面使用 await ,很简单,只需在 then 后面的回调函数中加 async 即可
xxx.then(async (res) => { ... }

都用了async和await了,还要then干什么,了解一下什么是async和await,楼上的回答可以的