0

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 />.

Mathias-S
  • 787
  • 3
  • 9

1 Answers1

3

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}
Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25