Svelte 5 just added a way to use async function in components. This is from
Rich Harris talk
The simplest component
<script>
async function multiply(x, y) {
let uri = `/multiply?x=${x}&y=${y}`
let rsp = await fetch(uri)
let resp = await rsp.text();
return parseInt(resp);
}
let n = $state(2)
</script>
<div>{n} * 2 = {await multiply(n, 2)}</div>
Previously you couldn’t do {await multiply(n, 2)
because Svelte didn’t understand promises. Now you can.
Aborting outdated requests
Imagine getting search results from a server based on what you type in an input box.
If you type foo
, we first send request for f
, then for fo
then for foo
at which point we don’t care about the results for f
and fo
. Svelte 5 can handle aborting outdated requests:
<script>
import { getAbortSignal } from "svelte";
let search = $state("")
const API = "https://dummyjson.com/product/search";
const response = $derived(await fetch(`${API}?q=${search}`), {
signal: getAbortSignal()
})
</script>
<input bind:value={search}>
<svelte:boundary>
<ul>
{#each (await response.json().products as product)}
<li>{product.title}</li>
{/each}
</ul>