Async Handling asynchronous operations in templates Guide
Categories

Async

Using Async

Async blocks handle promises directly in templates. They create reactive contexts that automatically re-execute when reactive dependencies change.

Async

You can use async to specify content that should only render after a promise is resolved like an API request.

{#async fetchUsers as users}
<p>Found {users.length} users</p>
{#each users as user}
<li>{user.name}</li>
{/each}
{/async}

Loading

To specify content that should render while the promise has not yet resolved you can use a loading block.

{#async getResults as result}
Result is <span>{result}</span>.
{loading}
Loading results..
{/async}

You can also use the alias before

{#async getResults as result}
Result is <span>{result}</span>.
{before}
Loading results..
{/async}

Error Handling

You can use an error block to handle if a promise triggers an error.

{#async getResults as result}
Result is <span>{result}</span>.
{error as e}
<p>Failed: {e.message}</p>
{/async}

You can also use the alias catch

{#async getResults as result}
Result is <span>{result}</span>.
{catch as e}
<p>Failed: {e.message}</p>
{/async}

Basic Example

The following example shows basic usage of an async block.

Special Values

This

When no as value is used for an async block it will be aliased to this for that block

{#async getResults}
Result is <span>{this}</span>.
{error}
<p>Failed: {this.message}</p>
{/async}

Reactivity

Async blocks are reactive contexts. Reactive contexts will rerun whenever signals like state or settings are modified.

Using Reactivity for Async

Reactive contexts can be particularly useful for async operations that should rerun whenever a set of values change.

For more information about reactivity in components see the dedicated reactivity guide

const defaultState = {
searchTerm: undefined
};
{#if searchTerm}
{#async getResults searchTerm as results}
{#each result in results}
<li>{result}</li>
{/each}
{/async}
{/if}

Reactivity Example

The following shows a real-world example of returning search results using a reactive searchTerm.

Previous
Loops
Next
Slots