0
0
SvelteHow-ToBeginner · 3 min read

How to Use {#await} Block in Svelte for Async Handling

In Svelte, use the {#await} block to handle promises directly in your template. It lets you show a loading state while waiting, display the resolved value when done, and handle errors with an {:catch} block.
📐

Syntax

The {#await} block in Svelte has three parts:

  • {#await promise}: Starts waiting for the promise.
  • {:then value}: Runs when the promise resolves, with value as the result.
  • {:catch error}: Runs if the promise rejects, with error as the error object.

You can also add a loading state between {#await} and {:then}.

svelte
{#await promise}
  <p>Loading...</p>
{:then value}
  <p>Result: {value}</p>
{:catch error}
  <p>Error: {error.message}</p>
{/await}
💻

Example

This example shows how to fetch user data with a promise and display loading, success, and error states using the {#await} block.

svelte
<script>
  let userPromise = fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(res => {
      if (!res.ok) throw new Error('Failed to fetch user');
      return res.json();
    });
</script>

{#await userPromise}
  <p>Loading user data...</p>
{:then user}
  <h2>{user.name}</h2>
  <p>Email: {user.email}</p>
{:catch error}
  <p style="color: red;">Error: {error.message}</p>
{/await}
Output
Loading user data... (then shows user name and email) or Error message if fetch fails
⚠️

Common Pitfalls

Common mistakes when using {#await} include:

  • Not providing a loading state, which can confuse users.
  • Forgetting the {:catch} block, so errors are not handled.
  • Using a non-promise value, which breaks the block.

Always ensure your variable is a promise and handle all three states for good user experience.

svelte
<!-- Wrong: no loading or catch -->
{#await promise}
  <!-- nothing here -->
{:then data}
  <p>{data}</p>
{/await}

<!-- Right: with loading and catch -->
{#await promise}
  <p>Loading...</p>
{:then data}
  <p>{data}</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 between {#await} and {:then}
  • Success: {:then value} block with resolved data
  • Error: {:catch error} block for rejected promises
  • End: Close with {/await}

Key Takeaways

Use {#await} to handle promises with loading, success, and error states in Svelte templates.
Always include a loading state and an error catch block for better user experience.
The {:then} block receives the resolved promise value to display.
The {:catch} block handles any errors from the promise.
Ensure the variable used is a promise; otherwise, the block will not work correctly.