javascript / intermediate
Snippet
Declarative Async Handling with Await Blocks
Svelte's #await block allows you to handle promises directly in your markup. It provides a clean way to manage the three states of an asynchronous operation: pending, fulfilled, and rejected, without needing extra state variables for loading or error flags.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
<script>let promise = fetch('https://api.example.com/data').then(res => res.json());</script>{#await promise}<p>Loading data...</p>{:then data}<p>Result: {data.value}</p>{:catch error}<p style="color: red">Error: {error.message}</p>{/await}
svelte
Breakdown
1
{#await promise}
Starts the block and subscribes to the provided promise.
2
{:then data}
Defines the template to render when the promise resolves successfully.
3
{:catch error}
Defines the template to render if the promise is rejected.