javascript / intermediate
Snippet
Declarative Promise Handling with Await Blocks
Svelte allows you to handle asynchronous Promises directly within the markup. This avoids the need for intermediate state variables like 'isLoading' or 'error' in your script logic.
snippet.js
1
2
3
4
5
6
7
{#await fetchUserData()}<p>Fetching user...</p>{:then user}<p>Welcome back, {user.name}!</p>{:catch error}<p style="color: red">{error.message}</p>{/await}
svelte
Breakdown
1
{#await fetchUserData()}
Initiates the tracking of a Promise-returning function directly in the template.
2
{:then user}
The block that renders once the Promise resolves, providing the result as a local variable.
3
{:catch error}
The error block that renders if the Promise is rejected, capturing the exception.