0 day streak
javascript / beginner
Snippet

Streaming Asynchronous Promises via Svelte Await Blocks

The `{#await}` block allows components to handle pending, resolved, and rejected Promise states declaratively in markup without maintaining multiple manual status flags.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script>
async function fetchGreeting() {
const response = await fetch('https://api.example.com/greeting');
const data = await response.json();
return data.message;
}
let greetingPromise = fetchGreeting();
</script>
{#await greetingPromise}
<p>Loading greeting...</p>
{:then message}
<p>Server message: {message}</p>
{:catch error}
<p>Failed to load: {error.message}</p>
{/await}
svelte
Breakdown
1
let greetingPromise = fetchGreeting();
Assigns an unresolved Promise to a variable accessible by the template.
2
{#await greetingPromise}
Renders the initial fallback state while the Promise is pending resolution.
3
{:then message}
Renders once the Promise successfully resolves, binding its resolved value to message.
4
{:catch error}
Renders if the Promise rejects, exposing the thrown error object.
5
{/await}
Closes the asynchronous template block.