javascript / beginner
Snippet
Async Templates with Await Blocks
Svelte allows you to handle JavaScript Promises directly in your HTML templates using await blocks, making it easy to manage loading and error states.
snippet.js
1
2
3
4
5
6
7
{#await fetchUser()}<p>Loading...</p>{:then user}<p>Hello, {user.name}!</p>{:catch error}<p>Error: {error.message}</p>{/await}
svelte
Breakdown
1
{#await fetchUser()}
Starts the block and executes the asynchronous function.
2
{:then user}
Defines the template to show once the Promise resolves successfully.
3
{:catch error}
Defines the template to show if the Promise is rejected with an error.