Ctrl + K
to search...
Home
Software
Contact Me

Using await in Svelte 5 components

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 a request for f, then for fo, and 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>
til svelte webdev javascript programming

Related articles