How to Use Await in Svelte: Simple Async Handling
In Svelte, you use the
await block inside your component's markup to handle promises asynchronously. It lets you show loading, success, and error states declaratively without extra JavaScript code.Syntax
The await block in Svelte has three parts: {#await promise} to start waiting, :then value to handle the resolved value, and :catch error to handle errors. You can also add a loading state between {#await} and :then.
svelte
<script> let promise = fetchData(); </script> {#await promise} <p>Loading...</p> {:then data} <p>Data loaded: {JSON.stringify(data)}</p> {:catch error} <p>Error: {error.message}</p> {/await}
Example
This example fetches user data asynchronously and shows loading, success, and error messages automatically using the await block.
svelte
<script> async function fetchUser() { const res = await fetch('https://jsonplaceholder.typicode.com/users/1'); if (!res.ok) throw new Error('Failed to fetch user'); return await res.json(); } let userPromise = fetchUser(); </script> {#await userPromise} <p>Loading user info...</p> {:then user} <h2>{user.name}</h2> <p>Email: {user.email}</p> {:catch error} <p>Error: {error.message}</p> {/await}
Output
<p>Loading user info...</p> (then after fetch) <h2>Leanne Graham</h2><p>Email: Sincere@april.biz</p>
Common Pitfalls
- Not initializing the promise before using
{#await}causes errors. - Forgetting to handle the
:catchblock can leave errors unshown. - Trying to use
awaitinside script tags withoutasyncfunctions won't work.
svelte
<script> // Wrong: promise not defined before await block </script> {#await undefinedPromise} <p>Loading...</p> {:then data} <p>{data}</p> {/await} <script> // Right: define promise first let promise = fetchData(); </script> {#await promise} <p>Loading...</p> {:then data} <p>{data}</p> {:catch error} <p>{error.message}</p> {/await}
Quick Reference
| Part | Description |
|---|---|
| {#await promise} | Starts waiting for the promise to resolve or reject |
| :then value | Runs when the promise resolves, with the resolved value |
| :catch error | Runs if the promise rejects, with the error object |
| Loading block | Content between {#await} and :then shown while waiting |
Key Takeaways
Use Svelte's {#await} block to handle promises directly in markup.
Always provide loading, success (:then), and error (:catch) states for good UX.
Initialize your promise before using it in the await block to avoid errors.
Avoid using await inside script without async functions; use the await block instead.
The await block keeps your code clean by managing async states declaratively.