Part 1 / Logic / Await blocks
Most web applications have to deal with asynchronous data at some point. Svelte makes it easy to await the value of promises directly in your markup:
{#await promise}
<p>...waiting</p>
{:then number}
<p>The number is {number}</p>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}
Only the most recent
promise
is considered, meaning you don't need to worry about race conditions.
If you know that your promise can't reject, you can omit the catch
block. You can also omit the first block if you don't want to show anything until the promise resolves:
{#await promise then number}
<p>The number is {number}</p>
{/await}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script>
async function getRandomNumber() {
// Fetch a random number between 0 and 100
// (with a delay, so that we can see it)
const res = await fetch('/random-number');
if (res.ok) {
return await res.text();
} else {
// Sometimes the API will fail!
throw new Error('Request failed');
}
}
let promise = getRandomNumber();
function handleClick() {
promise = getRandomNumber();
}
</script>
<button on:click={handleClick}>
generate random number
</button>
<!-- replace this element -->
<p>{promise}</p>
initialising