Mathias-S
Mathias-S

Reputation: 805

Svelte: How to display something only when a promise is not pending?

In Svelte's tutorial on await blocks and promises, they show how to display a certain text when a promise is awaiting/resolved/rejected.

But how can you show an element when something is not loading? I.e. when the promise has either been resolved or rejected (without duplicating the button in both {:then} and {:catch}, of course)

What I'm looking to do is the following:

{#await promise}
{:then number}
    <MyElement />
{:catch error}
    <MyElement />
{/await}

But without duplicating <MyElement />.

Upvotes: 0

Views: 1245

Answers (1)

Dhananjai Pai
Dhananjai Pai

Reputation: 6015

According to the Promises API (and this question, there is no off-the-shelf way to know if a promise has resolved)

You can create a flag that updates when the promise is resolved like

// in <script>
let resolved;
promise.then(x => resolved = true).catch(x => resolved = true);

and in the end, do

{#if resolved}
 <MyElement />
{/if}

Upvotes: 4

Related Questions