0
0
SvelteHow-ToBeginner · 3 min read

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 :catch block can leave errors unshown.
  • Trying to use await inside script tags without async functions 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

PartDescription
{#await promise}Starts waiting for the promise to resolve or reject
:then valueRuns when the promise resolves, with the resolved value
:catch errorRuns if the promise rejects, with the error object
Loading blockContent 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.