如何在 Vue.js 中使用 async/await?

新手上路,请多包涵

我是 ES7 的新手

我想在 Vue.js 中使用 async/await

这是我的代码

created (){
    this.getA()
    console.log(2)
    this.getB()
},
methods : {
    getA (){
        console.log(1)
    },
    getB (){
        console.log(3)
    }
}

它返回

1
2
3

但是当我将它与 axios 一起使用时,

 created (){
    this.getA()
    console.log(2)
    this.getB()
},
methods : {
    getA (){
        $axios.post(`/getA`,params){
        .then((result) => {
            console.log(1)
        })
    },
    getB (){
        console.log(3)
    }
}

它返回

2
3
1

所以我想在该代码中添加 async/await 。

如何使用异步/等待?

我试过了

async created (){
    await this.getA()
    console.log(2)
    await this.getB()
},
methods : {
    getA (){
        $axios.post(`/getA`,params){
        .then((result) => {
            console.log(1)
        })
    },
    getB (){
        console.log(3)
    }
}

它返回相同的结果。

原文由 USER 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 543
2 个回答

您必须使用 thenawait 不能同时使用,如下所示:

如果使用 then

 created () {
    this.getA().then((result) => {
            console.log(1)
            console.log(2)
            this.getB()
        })
},
methods : {
    getA () {
        return $axios.post(`/getA`,params);
    },
    getB (){
        console.log(3)
    }
}

如果使用 await

 async created (){
    await this.getA()
    console.log(1)
    console.log(2)
    this.getB()
},
methods : {
    getA : async() => {
        return $axios.post(`/getA`,params);
    },
    getB : () => {
        console.log(3)
    }
}

请注意,在调用 getB() 时,您不需要 thenawait 因为它不是异步的

原文由 Thanthu 发布,翻译遵循 CC BY-SA 4.0 许可协议

与@thanthu 所说的不同,您可以同时使用 then 和 await 。在您的第一篇文章中,您只错过了在 getA 方法中添加 return

 async created (){
    await this.getA()
    console.log(2)
    await this.getB()
},
methods : {
    getA() {
        return $axios
            .post(`/getA`,params){
            .then((result) => {
                console.log(1)
            });
    },
    getB() {
        console.log(3)
    }
}

原文由 Stéphane Damon 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题