javascript / beginner
Snippet
Fetching Profile Data Asynchronously via Async Await in Vue
The async and await keywords provide a clean, readable syntax to work with asynchronous Promise-based operations. In Vue components, async functions in lifecycle hooks like onMounted pause execution until network requests resolve before updating reactive data properties.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { ref, onMounted } from 'vue';export default {setup() {const user = ref(null);const isLoading = ref(true);async function loadUserProfile() {isLoading.value = true;const response = await fetch('https://api.example.com/user/1');user.value = await response.json();isLoading.value = false;}onMounted(loadUserProfile);return { user, isLoading };}};
vue
Breakdown
1
async function loadUserProfile() {
Declares an asynchronous function that can pause execution using the await keyword.
2
const response = await fetch('https://api.example.com/user/1');
Waits for the network HTTP request Promise to complete before continuing.
3
user.value = await response.json();
Awaits the parsing of the response body as JSON and assigns it to the reactive user ref.
4
onMounted(loadUserProfile);
Triggers the asynchronous load function when the Vue component is mounted to the DOM.