javascript / beginner
Snippet
Fetching Remote User Profiles with Async Await and Try Catch
When performing asynchronous HTTP requests in Vue components, handling network failures and HTTP errors gracefully is crucial. Using async/await within a try/catch/finally block guarantees that error states are caught and the loading indicator is always reset, keeping the user interface reliable and responsive.
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 user = ref(null);const errorMessage = ref('');const isLoading = ref(false);async function loadUserData(userId) {isLoading.value = true;errorMessage.value = '';try {const response = await fetch(`https://api.example.com/users/${userId}`);if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}user.value = await response.json();} catch (error) {errorMessage.value = error.message;} finally {isLoading.value = false;}}
vue
Breakdown
1
async function loadUserData(userId) {
Declares an asynchronous function allowing the use of await for handling promises.
2
try {
Starts the execution block where network requests and response parsing are attempted.
3
const response = await fetch(`https://api.example.com/users/${userId}`);
Pauses execution until the remote HTTP fetch request resolves to a Response object.
4
if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
Checks if the HTTP status code is outside the 200-299 range and throws an error if so.
5
user.value = await response.json();
Parses the incoming JSON body asynchronously and assigns the data to the reactive user ref.
6
} catch (error) { errorMessage.value = error.message; }
Catches any network or response errors and stores the message in a reactive variable for display.
7
} finally { isLoading.value = false; }
Executes regardless of success or failure to guarantee the loading indicator turns off.