Performance: Await blocks ({#await})
This affects how asynchronous data loading impacts page rendering and user interaction responsiveness.
<script> let promise = fetch('/api/data').then(res => res.json()); </script> {#await promise} <p>Loading...</p> {:then data} <p>{data.value}</p> {:catch error} <p>Error loading data</p> {/await}
<script> let data = fetch('/api/data').then(res => res.json()); </script> {#if !data} Loading... {/if} {#if data} <p>{data.value}</p> {/if}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Incorrect promise handling without await block | Multiple conditional DOM checks | Renders immediately but never updates with data | Paints incorrect/empty content, no data update | [X] Bad |
| Proper await block with fallback and then blocks | Single DOM update on promise resolution | Immediate fallback render, single reflow on data | Lower paint cost with incremental updates | [OK] Good |
{#await} block in Svelte?{#await} in Svelte{#await} block is designed to handle promises and asynchronous data by showing different UI states while waiting, on success, or on error.{#await}.dataPromise?{#await promise} followed by the block content and closed with {/await}.{#await fetchData()}
Loading...
:then data
{data.message}
:catch error
Error: {error.message}
{/await}fetchData() returns a promise that resolves to { message: 'Hello!' }?fetchData() resolves successfully with an object containing { message: 'Hello!' }.:then block runs, displaying {data.message} which is 'Hello!'.{#await loadData()}
Loading...
:then result
{result}
:catch
Error occurred
{/await}:catch block must include a variable name to capture the error, like :catch error.:catch without a variable name, which is a syntax error.userData promise, display the user's name on success, and show a retry button on error. Which Svelte await block correctly implements this behavior?{user.name}
:then user, and shows a retry button with error variable error in :catch.Loading...
{user.name}
{user.name}
:catch.{user.name}
{user.name}
Pass the test and this pattern moves unknown