Sometimes, we want to use async and await in Vue.js.
In this article, we’ll look at how to use async and await in Vue.js.
How to use async and await in Vue.js?
To use async and await in Vue.js, we can add async
and await
in our component methods and hooks.
For instance, we write
<script>
export default {
//...
async created() {
await this.getA();
console.log(1);
this.getB();
},
methods: {
getA: async () => {
return $axios.post(`/getA`, params);
},
getB: () => {
console.log(3);
},
},
//...
};
</script>
to make the created
hook an async method.
We use await
to wait for the getA
method to finish before running the rest of the code.
getA
returns a promise so we can use await
to wait for it to finish.
Conclusion
To use async and await in Vue.js, we can add async
and await
in our component methods and hooks.
2 replies on “How to use async and await in Vue.js?”
Doesn’t declaring methods as arrow functions break the ‘this’ transference vue performs? The docs explicitly say not to declare methods with arrow funtions.
The method can be declared with arrow functions in the example because it doesn’t reference this.
The ones that reference this aren’t arrow functions.