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 value}
<p>the value is {value}</p>
{/await}
App.svelte
xxxxxxxxxx
25
1
<script>
2
let promise = getRandomNumber();
3
4
async function getRandomNumber() {
5
const res = await fetch(`tutorial/random-number`);
6
const text = await res.text();
7
8
if (res.ok) {
9
return text;
10
} else {
11
throw new Error(text);
12
}
13
}
14
15
function handleClick() {
16
promise = getRandomNumber();
17
}
18
</script>
19
Console
xxxxxxxxxx
87
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
detach,
6
element,
7
init,
8
insert,
9
listen,
10
noop,
11
safe_not_equal,
12
set_data,
13
space,
14
text
15
} from "svelte/internal";
16
xxxxxxxxxx
87
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
detach,
6
element,
7
init,
8
insert,
9
listen,
10
noop,
11
safe_not_equal,
12
set_data,
13
space,
14
text
15
} from "svelte/internal";
16
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */
xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */