
How to Use Promises in Svelte
To use pending promises inside a template in Svelte, you can use the await
template expression.
Copied to clipboard!
{#await promise}
<span>Loading... please wait</span>
{:then user}
<h1>Hello {user.name} π</h1>
{:catch error}
<span>Something went wrong: {error.message} π€</span>
{/await}
This way you can render content based on the state of the promise. If you don't care about promise rejection, you can leave out the catch
clause:
Copied to clipboard!
{#await promise}
<span>Loading... please wait</span>
{:then user}
<h1>Hello {user.name} π</h1>
{/await}
If you also don't want to care about pending states β which you should β then you can also leave out the first block and shorten it down to:
Copied to clipboard!
{#await promise then user}
<h1>Hello {user.name} π</h1>
{/await}


Resources:
π More Webtips

Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: