Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
Promises are an awesome tool we have at our disposal to work with asynchronous events in JavaScript.
The relatively recent introduction of the await
syntax in ES2017 made using promises even simpler.
Svelte provides us the {#await}
syntax in templates to directly work with promises at the template level.
We can wait for promises to resolve, and define a different UI for the various states of a promise: unresolved, resolved and rejected.
Here’s how it works. We define a promise, and using the {#await}
block we wait for it to resolve.
Once the promise resolves, the result is passed to the {:then}
block:
<script>
const fetchImage = (async () => {
const response = await fetch('https://dog.ceo/api/breeds/image/random')
return await response.json()
})()
</script>
{#await fetchImage}
<p>...waiting</p>
{:then data}
<img src={data.message} alt="Dog image" />
{/await}
You can detect a promise rejection by adding a {:catch}
block:
{#await fetchImage}
<p>...waiting</p>
{:then data}
<img src={data.message} alt="Dog image" />
{:catch error}
<p>An error occurred!</p>
{/await}
Run the example: https://svelte.dev/repl/70e61d6cc91345cdaca2db9b7077a941
Download my free Svelte Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More svelte tutorials:
- Getting started with Svelte - a short tutorial
- How to work with props in Svelte
- How to import components in Svelte
- How to export functions and variables from a Svelte component
- Svelte templates: conditional logic
- How to rerender a Svelte component on demand
- Svelte Slots
- How to add comments in Svelte templates
- Svelte Bindings
- Handling State Updates in Svelte
- Reactive Statements in Svelte
- Svelte Lifecycle Events
- Svelte templates: loops
- Resolve promises in Svelte templates
- Working with events in Svelte
- Cross-component State Management in Svelte
- How to access a URL parameter in Sapper outside of script module
- How to dynamically apply CSS in Svelte
- How to redirect to a URL in Sapper
- How to simulate a for loop in Svelte templates