javascript / beginner
Snippet
Retrieving Remote HTTP Data Using Async-Await Syntax
The `async`/`await` syntax enables non-blocking asynchronous operations to be written with clear, linear execution flow. Checking `response.ok` ensures that network-level HTTP status failures (such as 404 or 500) are caught and handled appropriately alongside data deserialization.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
async function fetchUserProfile(userId) {const response = await fetch(`https://api.example.com/users/${userId}`);if (!response.ok) {throw new Error(`HTTP error! Status: ${response.status}`);}const userData = await response.json();return userData;}
svelte
Breakdown
1
async function fetchUserProfile(userId) {
Defines an asynchronous function that implicitly returns a Promise.
2
const response = await fetch(`https://api.example.com/users/${userId}`);
Pauses function execution until the network request completes and resolves to a Response object.
3
if (!response.ok) {
Verifies that the HTTP status code falls within the successful 200–299 range.
4
throw new Error(`HTTP error! Status: ${response.status}`);
Explicitly throws an Error if the server responded with a client or server error code.
5
}
Closes the status check condition.
6
const userData = await response.json();
Awaits parsing of the incoming response body stream into a JavaScript object.
7
return userData;
Returns the parsed user profile object to the caller.
8
}
Closes the async function body.