javascript / beginner
Snippet
Managing Asynchronous State and Rejections with Await Blocks
Asynchronous JavaScript functions return Promises that transition through pending, resolved, and rejected states. Svelte's await block natively mirrors this lifecycle directly in markup, providing distinct blocks for the pending state, the fulfilled payload, and error boundary handling without requiring manual boolean flags.
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 fetchRandomFact() {const res = await fetch('https://api.sampleapis.com/futurama/info');if (!res.ok) {throw new Error(`HTTP error! status: ${res.status}`);}return res.json();}let factPromise = fetchRandomFact();</script>{#await factPromise}<p>Loading facts...</p>{:then data}<p>{data[0].synopsis}</p>{:catch error}<p style="color: red;">Failed to load: {error.message}</p>{/await}
svelte
Breakdown
1
async function fetchRandomFact() { ... }
Declares an asynchronous function that fetches remote data and returns a Promise.
2
if (!res.ok) { throw new Error(...); }
Checks the HTTP status and throws an error if the network request failed.
3
{#await factPromise} ... {:then data} ... {:catch error}
Handles the pending, fulfilled, and rejected states of the Promise natively.