Building Async Components in Svelte
- 1 minute read
The below Svelte component shows a “loading” placeholder text for one second, after which a “loaded” text is displayed:
{#await new Promise(resolve => setTimeout(resolve, 1000))}
<p>Loading...</p>
{:then data}
<p>Loaded</p>
{:catch error}
<p>Oops! Error: {error.message}</p>
{/await}
The most common use case I’ve seen for using Svelte’s built-in await block is for displaying a placeholder (such as a loading spinner) during an API request.
By the way, the catch
block at the end of the above example is actually optional - although I would personally generally recommend it for reliability purposes.
Conclusion
In any case, I hope this helped you build some asynchronous Svelte components!