0
0
Svelteframework~5 mins

Await blocks ({#await}) in Svelte

Choose your learning style9 modes available
Introduction

Await blocks let you show different content while waiting for something to finish, like loading data. This makes your app feel smooth and clear.

When fetching data from a server and you want to show a loading message.
When waiting for a file to upload and you want to show progress or a spinner.
When performing a slow calculation and you want to keep the user informed.
When loading images or resources that take time to appear.
When you want to handle errors if the waiting task fails.
Syntax
Svelte
{#await promise}
  <!-- content while waiting -->
{:then value}
  <!-- content when promise resolves -->
{:catch error}
  <!-- content if promise rejects -->
{/await}

The promise is a JavaScript Promise you want to wait for.

You can show different content for loading, success, and error states.

Examples
Shows a loading message while fetchData() runs, then shows data or error.
Svelte
{#await fetchData()}
  <p>Loading...</p>
{:then data}
  <p>Data loaded: {data}</p>
{:catch error}
  <p>Error: {error.message}</p>
{/await}
Simple await block without error handling.
Svelte
{#await promise}
  <p>Please wait...</p>
{:then result}
  <p>Result: {result}</p>
{/await}
Shows a spinner component while waiting, then result or error.
Svelte
{#await slowTask()}
  <Spinner />
{:then value}
  <p>Done: {value}</p>
{:catch err}
  <p>Oops! {err.message}</p>
{/await}
Sample Program

This Svelte component waits 2 seconds, then shows a success message. While waiting, it shows a loading message. If an error happened, it would show an error message.

Svelte
<script>
  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve('Hello from await block!'), 2000);
  });
</script>

{#await promise}
  <p>Loading message: Please wait 2 seconds...</p>
{:then message}
  <p>Success message: {message}</p>
{:catch error}
  <p>Error message: {error.message}</p>
{/await}
OutputSuccess
Important Notes

Always include a loading state so users know something is happening.

Use the {:catch} block to handle errors gracefully.

Await blocks keep your UI reactive and clean without extra code.

Summary

Await blocks help show loading, success, and error states for promises.

They make apps feel responsive and clear to users.

Use them whenever you wait for something that takes time.