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.