How to Use Await Block for Data in Svelte: Simple Guide
In Svelte, use the
{#await} block to handle promises directly in your markup. It lets you show loading, success, and error states by writing {#await promise}, :then, and :catch blocks inside your component.Syntax
The {#await} block in Svelte handles promises with three parts:
{#await promise}: Starts waiting for the promise.:then variable: Runs when the promise resolves, giving you the result.:catch error: Runs if the promise rejects, giving you the error.
You can also add a loading state between {#await} and :then.
svelte
{#await promise}
<p>Loading...</p>
{:then data}
<p>Data: {data}</p>
{:catch error}
<p>Error: {error.message}</p>
{/await}Example
This example shows how to fetch user data asynchronously and display loading, success, or error messages using the {#await} block.
svelte
<script> // Simulate fetching user data with a promise function fetchUser() { return new Promise((resolve, reject) => { setTimeout(() => { // Change to reject(new Error('Failed to load')) to test error resolve({ name: 'Alice', age: 30 }); }, 1500); }); } let userPromise = fetchUser(); </script> {#await userPromise} <p>Loading user data...</p> {:then user} <p>User name: {user.name}</p> <p>User age: {user.age}</p> {:catch error} <p>Error loading user: {error.message}</p> {/await}
Output
Loading user data... (for 1.5 seconds) then
User name: Alice
User age: 30
Common Pitfalls
Common mistakes when using {#await} include:
- Not providing a loading state, which can confuse users.
- Forgetting to handle errors with
:catch, causing silent failures. - Using a non-promise value, which makes the block not work as expected.
Always ensure your variable is a promise and handle all three states for best user experience.
svelte
<!-- Wrong: no loading or catch --> {#await userPromise} <!-- nothing here --> {:then user} <p>{user.name}</p> {/await} <!-- Right: with loading and catch --> {#await userPromise} <p>Loading...</p> {:then user} <p>{user.name}</p> {:catch error} <p>Error: {error.message}</p> {/await}
Quick Reference
Use this quick guide when working with {#await} blocks:
- Start:
{#await promise} - Loading: Content before
:thenruns while waiting - Success:
{:then data}shows resolved data - Error:
{:catch error}shows errors - End: Close with
{/await}
Key Takeaways
Use the {#await} block to handle promises directly in Svelte markup.
Always provide loading, success (:then), and error (:catch) states for good UX.
The variable inside {#await} must be a promise to work correctly.
You can show a loading message before the promise resolves or rejects.
Handle errors explicitly with :catch to avoid silent failures.