javascript / beginner
Snippet
Managing Asynchronous Promise States via Svelte Await Blocks
Svelte's {#await} block simplifies handling JavaScript Promises directly in the view. It seamlessly transitions between pending, resolved ({:then}), and rejected ({:catch}) asynchronous states without requiring manual state flags for loading or errors.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script>async function fetchSystemHealth() {const response = await fetch("https://api.example.com/health");if (!response.ok) {throw new Error(`HTTP error ${response.status}`);}return response.json();}let healthPromise = fetchSystemHealth();</script>{#await healthPromise}<p>Checking service status...</p>{:then data}<p class="online">Service OK: {data.status}</p>{:catch error}<p class="error">Health check failed: {error.message}</p>{/await}
svelte
Breakdown
1
throw new Error(`HTTP error ${response.status}`);
Instantiates and throws an error if the HTTP response status is not successful.
2
let healthPromise = fetchSystemHealth();
Stores the unresolved Promise returned by calling the async function.
3
{#await healthPromise}
Displays loading placeholder content while the Promise remains pending.
4
{:catch error}
Catches any rejected error from the Promise and renders the error message.