javascript / beginner
Snippet
Fetching Remote Data with Async/Await and Error State
Asynchronous operations like network requests require handling pending, success, and error states. Combining `async/await` with `try...catch...finally` ensures that loading flags are always reset while network failures are properly isolated and displayed.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { ref } from 'vue';const profile = ref(null);const isPending = ref(false);const fetchError = ref(null);async function loadUserProfile(userId) {isPending.value = true;fetchError.value = null;try {const response = await fetch(`https://api.example.com/users/${userId}`);if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}profile.value = await response.json();} catch (err) {fetchError.value = err.message;} finally {isPending.value = false;}}
vue
Breakdown
1
async function loadUserProfile(userId) {
Defines an asynchronous function capable of awaiting Promise-based operations.
2
const response = await fetch(`https://api.example.com/users/${userId}`);
Pauses function execution until the fetch network request promise resolves.
3
profile.value = await response.json();
Parses the response stream into JSON and stores the result in reactive state.
4
finally { isPending.value = false; }
Guarantees that the loading indicator flag is deactivated regardless of success or failure.