Use `await` in Vue components with async methods
April 4, 2022 ‐ 2 min read
The already not-so-recent-anymore ES7 changes to JavaScript introduced the async
and await
keywords. They allow for some syntactic sugar around JavaScript Promises.
They can make asynchronous code more easy to read, and therefore worthy to look into for your Vue.js methods.
You can use async
and await
for your lifecycle hooks, methods and watcher functions. One exception here is computed properties, which don’t allow the use of async
and await
.
In order to use await
in the methods of you Vue component you prefix the method name with the async
keyword. See the following example, where you see custom async methods as well as async lifecycle hooks such as mounted
and created
.
<script>
export default {
data() {
return {
token: undefined,
user: undefined,
};
},
async created() {
this.token = await fetchUser();
},
async mounted() {
this.user = await this.fetchUser();
},
methods: {
async getToken() {
const token = await Cookie.read("token");
return token;
},
async fetchUser() {
const user = await api.get("user", { token: this.token });
return user;
},
},
};
</script>
Browser support
Although the async
and await
should be available in all recently updated modern browsers, you might want to double check the browser support just in case.
If you need to support Internet Explorer in you Vue app than using a JavaScript transpiler like Babel will allow you to use async
/await
in your Vue methods.