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

How to use async/await in Vue.js?

我是 ES7 新手

我想在 Vue.js

中使用 async/await

这是我的代码

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

它returns

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)
    }
}

它returns

2
3
1

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

如何使用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)
    }
}

它returns相同的结果。

试试这个

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

您必须使用 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 所说的不同,您可以同时使用 then 和 await。 在您的第一个 post 中,您只是错过了在 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)
    }
}

Vuejs,以 Axios API 请求为例。代码之间的更多细节

  methods: {
    async getA(data, type) {
      console.log("This is a API calls, that the response time is vary.");

      const result = await this.getSources();
      
      console.log("Do what you want after completing the prev job.");
    },
    getSources() {
      return new Promise(resolve => {

        // Here the point is the resolve that you should resolve('something');.
        this.axios
          .get("/api/sources")
          .then((resp) => {
            this.sources = resp.data;
            resolve('resolved');
          })
          .catch(() => {
            resolve('rejected');
          });
      });
    },
  },