Order Fried Rice at Mrs. Sri's stall and you get a queue number slip. The slip isn't the food, it's a promise of food. While you wait, the board on the wall says "Cooking". When it's ready, the plate comes. If the gas runs out, the waiter says "Sorry, we can't".
In JavaScript, that queue slip is called a Promise: an object standing for a result that doesn't exist yet. Later it succeeds (resolves) with a value, or fails (rejects) with an error. The board on the wall is the {#await} block: it waits for a Promise and shows one of three states, while waiting, on success, or on failure.
Three states in one block
fetchMenu() pretends to ask a server for the menu, and the server answers after 800 ms:
<script>
function fetchMenu() {
return new Promise((resolve) => {
setTimeout(() => {
resolve([
{ name: "Fried Rice", price: 15 },
{ name: "Chicken Noodles", price: 12 },
{ name: "Iced Tea", price: 5 },
])
}, 800)
})
}
let promise = $state(fetchMenu())
</script>
{#await promise}
<p>Loading menu...</p>
{:then menu}
<ul>
{#each menu as m}
<li>{m.name} ${m.price.toFixed(2)}</li>
{/each}
</ul>
{:catch error}
<p>Failed: {error.message}</p>
{/await}
| Time | Promise state | Shows |
|---|---|---|
| 0 ms | waiting (pending) | Loading menu... |
| 800 ms | succeeded | Fried Rice $15.00, Chicken Noodles $12.00, Iced Tea $5.00 |
let promise = $state(fetchMenu())keeps the promise.$stateis there because the Reload button replaces this promise later.{#await promise}opens the block. What comes before{:then}shows while the promise isn't settled.{:then menu}shows when the promise succeeds. Its value is given the namemenu; any name works.{:catch error}shows when the promise fails.erroris the reason it failed, usually anErrorobject, so its message is read witherror.message.{/await}closes the block. Same pattern as{#if}and{#each}:#opens,:continues,/closes.- In the Lifecycle lesson, the same thing took
onMount,menu = await fetchMenu()and{#if menu.length === 0}. Here there's no extra variable, and the failure branch comes with it.
When it fails: {:catch}
Now the server is closed:
function fetchMenu() {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("The stall's server is closed")), 800)
})
}
At 0 ms it's still Loading menu.... At 800 ms, the {:catch error} branch replaces it: Failed: The stall's server is closed.
In a real app, the promise usually comes from fetch("/api/menu").then((r) => r.json()). Remember, fetch only fails when the network is down. A 404 or 500 answer still counts as a success, unless you write if (!r.ok) throw new Error("Failed to load the menu") yourself.
Without {:catch}
The same template without {:catch}. At 800 ms, Svelte removes Loading menu..., there's no branch it can show, so that part is empty. The error doesn't vanish: Svelte throws it again, and the console writes Uncaught (in promise) Error: The stall's server is closed. The customer only sees an empty page with no explanation. If the promise can fail, always write {:catch}.
Reloading: assign a new promise
<button onclick={() => (promise = fetchMenu())}>Reload</button>
promise = fetchMenu()is an assignment to a$statevariable, so Svelte sees a new promise. The block goes back toLoading menu..., then to{:then}or{:catch}depending on how that new promise ends.onclick={fetchMenu}alone changes nothing on screen. The function runs, but thepromisevariable isn't reassigned.- If the button is clicked twice and the first request is slower, Svelte only shows the result of the promise assigned last. The old result is thrown away when it arrives.
The short form
{#await promise then menu}
<p>{menu.length} dishes available</p>
{/await}
{#await promise then menu}has no waiting branch: nothing shows for 800 ms, then3 dishes available.{#await promise catch error}is the opposite: it only shows on failure.- If what's awaited isn't a Promise, for example
{#await 42}, the block goes straight to{:then}.
Exercise: three states
<script>
let promise = new Promise(resolve => {
setTimeout(() => resolve("Data loaded successfully!"), 100)
})
</script>
{#await promise}
<p>Loading...</p>
{:then data}
<p>{data}</p>
{:catch error}
<p>Error: {error.message}</p>
{/await}
For 100 ms the paragraph reads Loading..., then Data loaded successfully!. The checker waits until there's a <p> containing the word Data.
Svelte 5
The {#await} syntax is exactly the same in Svelte 4 and Svelte 5, so examples from older tutorials still hold. The only difference is the variable: Svelte 4 code writes a plain let promise = fetchMenu(), and its assignment is enough to trigger the block again. In a runes component a plain let isn't watched, so the promise the Reload button replaces is made with $state, as in the example above.
⚠️ Empty sections and promises that won't reload
- Not writing
{:catch}. On failure the part is empty and the error only shows in the console asUncaught (in promise). - Calling it again without assigning.
fetchMenu()alone triggers nothing. Writepromise = fetchMenu(), withpromisemade through$state. Ifpromiseis just a plainlet, the compiler warnsnon_reactive_updateand the block doesn't reload. awaitstraight in<script>. In the exercise editor (Svelte 5.16),let menu = await fetchMenu()gets through the compiler, but the component fails to run with aSyntaxError, because a component's<script>isn't an async function. Current Svelte refuses it at compile time with the errorexperimental_async:awaitat the top level of a component is only allowed when theexperimental.asynccompiler option istrue. That option exists since Svelte 5.36, and with itawaitcan be used in<script>and in markup, with<svelte:boundary>and apendingsnippet for the loading view. The feature is still experimental (its flag is planned to be removed in Svelte 6). For now, keep the promise, then hand it to{#await}.- A missing branch. The exercise checks for
#await,:thenand:catchin your code, and for a<p>that ends up containingData.
TL;DR: {#await promise} ... {:then menu} ... {:catch error} ... {/await} shows one of a Promise's three states: waiting, succeeded (its value becomes menu), or failed (the reason becomes error, its message error.message). Without {:catch}, a failed promise leaves an empty part and Uncaught (in promise) in the console. Reload by assigning a new promise, promise = fetchMenu(), to a variable made with $state(...); Svelte only shows the result of the latest promise. {#await promise then menu} is the short form with no waiting branch. The {#await} syntax is the same in Svelte 4 and Svelte 5. The exercise: <p>Loading...</p>, then <p>{data}</p> showing Data loaded successfully!, and <p>Error: {error.message}</p> in {:catch error}.
⚡ Three states in one block
Write:
{#await promise}
<p>Loading menu...</p>
{:then menu}
<ul>
{#each menu as m}
<li>{m.name} ${m.price.toFixed(2)}</li>
{/each}
</ul>
{:catch error}
<p>Failed: {error.message}</p>
{/await}
Meaning: What comes before {:then} shows while waiting. {:then menu} shows when the promise succeeds, with its value named menu. {:catch error} shows when it fails, and its message is read through error.message.
⚡ Don't forget {:catch}
Guess first: the same template without {:catch}, and the server is closed. What does the customer see?
That part is empty. The error doesn't vanish, the console writes Uncaught (in promise) Error: The stall's server is closed, but the customer only sees an empty page with no explanation.
Meaning: If the promise can fail, always write {:catch}.
⚡ Reload: assign a new promise
Write:
<button onclick={() => (promise = fetchMenu())}>Reload</button>
Guess first: if you write just onclick={fetchMenu}, does the screen change?
No. The function runs, but the promise variable isn't reassigned, so the block never learns there's a new promise.
Meaning: promise = fetchMenu() gives the $state variable a new promise, so the block goes back to Loading menu..., then to {:then} or {:catch}.