Svelte Await Blocks

An await block handles data that takes time to arrive, such as information fetched from a server. Svelte shows different content depending on whether the data is still loading, has arrived, or failed to arrive.

Why Await Blocks Matter

A request to a server rarely returns data instantly. A visitor's page needs something to display during that waiting period, rather than a blank gap. An await block manages this waiting period directly inside your markup.

Basic Await Block Syntax

<script>
  async function getUser() {
    const response = await fetch("https://example.com/api/user");
    return response.json();
  }

  let userPromise = getUser();
</script>

{#await userPromise}
  <p>Loading user data...</p>
{:then user}
  <p>Welcome, {user.name}</p>
{:catch error}
  <p>Something went wrong: {error.message}</p>
{/await}

The page shows a loading message first. Once the data arrives, the loading message swaps out for the welcome message. If the request fails instead, an error message appears in place of both.

Await Block Flow Diagram

userPromise starts
        |
        v
   Still waiting?
   /            \
 Yes             No
  |               |
  v               v
Show loading    Did it succeed?
message          /          \
                Yes          No
                 |             |
                 v             v
          Show user data   Show error message

The Three Branches Explained

The Pending Branch

The first section, before any colon-prefixed word, runs while the promise has not yet settled. This branch usually shows a spinner or a short loading message.

The Then Branch

The then branch runs once the promise resolves successfully. The word right after then, in this case user, holds the resolved value ready for display.

The Catch Branch

The catch branch runs if the promise fails for any reason, such as a network error or a server returning an error response. The word right after catch, in this case error, holds details about what went wrong.

A Simpler Version Without Error Handling

A short version skips the catch branch when a failure case does not need separate handling.

{#await userPromise then user}
  <p>Welcome, {user.name}</p>
{/await}

This shortcut works well for quick prototypes, though production pages usually benefit from handling failures explicitly.

Common Use Cases

  • Loading a user profile after visiting a page
  • Fetching a list of products from a shop's server
  • Loading search results after a visitor submits a query
  • Displaying weather data pulled from an external service

Triggering A New Request On Demand

Reassigning the promise variable inside an event handler restarts the await block, useful for a refresh button or a search field that fetches new results.

<script>
  async function getUser() {
    const response = await fetch("https://example.com/api/user");
    return response.json();
  }

  let userPromise = getUser();

  function refresh() {
    userPromise = getUser();
  }
</script>

<button on:click={refresh}>Refresh</button>

{#await userPromise}
  <p>Loading...</p>
{:then user}
  <p>{user.name}</p>
{/await}

Clicking refresh calls getUser again and stores a fresh promise, which sends the await block right back into its pending state until the new request finishes.

Key Points

  • An await block manages loading, success, and failure states together
  • The pending section shows while data has not yet arrived
  • The then section shows the resolved data once it arrives
  • The catch section shows an error message if the request fails

Leave a Comment

Your email address will not be published. Required fields are marked *