'How to switch from .then to async await in Vue JS
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.
Solution 1:[1]
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);
}
}
Solution 2:[2]
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);
})
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | MR Mark II |
