Home > Software design >  How to switch from .then to async await in Vue JS
How to switch from .then to async await in Vue JS

Time:02-12

I am wondering how to switch the created function that is already asynchronours via .then, to async await.

created() {
    this.$http.get("wp/v2/posts").then(
      response => {
        for (let post in response.data) {
          this.posts.push(response.data[post]);
        }
        this.$store.dispatch({
          type: "updatePost",
          value: this.posts
        });
      },
      error => {
        alert(error);
      }
    );
}

I could easily add async created() and await this.$http.get, but couldn't figure out on the error => {} part since the curly braces for responses will also be gone.

CodePudding user response:

Thanks for the suggestion on try and catch. Please correct me if I am wrong with this:

async created() {
    const response = await this.$http.get("wp/v2/posts")
    
    try {
      for (let post in response.data) {
        this.posts.push(response.data[post]);
      }
      this.$store.dispatch({
        type: "updatePost",
        value: this.posts
      });
    }
    catch (error) {
      alert(error);
    }
}

CodePudding user response:

I think you can use this instead of using try:

async created() {
  await this.$http.get("wp/v2/posts").then(response => {
    for (let post in response.data) {
      this.posts.push(response.data[post]);
    }
    this.$store.dispatch({
      type: "updatePost",
      value: this.posts
    });
  }).catch(function () {
    alert(error);
  })
}
  • Related