Home > Web Front-end > JS Tutorial > Running a Function When an #await Block resolves in Svelte(Kit)

Running a Function When an #await Block resolves in Svelte(Kit)

Patricia Arquette
Release: 2024-11-05 18:49:02
Original
184 people have browsed it

Skip To Content:

  • About the #await block in svelte
  • Run (trigger) a function when the #await block resolves or rejects
  • Fix undefined or any returned text showing up in browser
    • 1. Method 1 (Return empty strings):
    • 2. Method 2 (Hide the returned text from the function in the UI with CSS.)
      • PS: Need to employ a SvelteKit Dev? Contact me

About the #await block in svelte

The #await block in svelte is very handy for handling asynchronous data:

<script>
import Loader from "$components/forms/Helpers/Loader.svelte";

export let data;
// let's say data.myPromise is a promise.
</script>

{#await data.myPromise}
<!-- This is what shows while the promise is pending -->
<Loader />

{:then results}
<!-- Shows this if/when the promise resolves successfully -->
{#each results as result}
<li>{result}</li>
{/each}

{:catch error}
<!-- Shows this if/when the promise rejects -->
<p class="text-red">{error?.message ?? "Something went wrong"}</p>
{/await}
Copy after login

This is basically how the #await block works in svelte. It displays different content based on the state of a promise: a loading indicator while pending, results when resolved, and an error message if rejected.

But let's say I want a certain function to run when the promise has been resolved or rejected (like a toast).


Run (trigger) a function when the #await block resolves or rejects

Here's how you can run specific functions when the promise resolves or rejects:

<script>
import { toast } from "svelte-sonner";

/**
* Displays a success toast
* @param {number | string} resultsLength - Number of results
*/
function showSuccess (resultsLength) {
toast.success(`${resultsLength} result${resultsLength > 1 ? "s" : ""} retrieved!`)
}

/**
* Displays an error toast
* @param {string} [errorMessage] - Error message to display
*/
function showError(errorMessage) {
toast.error(`An Error Occured`, {
message: errorMessage ?? "Unknown Error"
})
}

</script>

{#await data.myPromise}
<!-- Displays while the promise is pending -->
<Loader />

{:then results}
<!-- Run showSuccess when the promise resolves -->
{showSuccess(results.length)}

  <!-- Display results -->
{#each results as result}
<li>{result}</li>
{/each}

{:catch error}
<!-- Run (trigger) showError when the promise rejects -->
{showError(error.message)}

  <!-- Display error message -->
<p class="text-red">{error?.message ?? "Something went wrong"}</p>
{/await}
Copy after login

Now, our function will run whenever the code block is reached.

  • showSuccess is called when the promise resolves, with the number of results as an argument.
  • showError is triggered if the promise rejects, displaying a custom error message.

One more thing though...

Fix undefined or any returned text showing up in browser

When these functions run, whatever is returned text will show up in the browser, because it's kind of a workaround. The syntax we used is usually to meant to show returned strings/numbers in the browser. Even returning nothing will return the default undefined. And this string (which usually make no sense), will be displayed to the end user. Something like this:
Running a Function When an #await Block resolves in Svelte(Kit)

Makes no sense to the end user ?‍♂️?‍♀️

So, make sure to return empty strings, or wrap the function in an hidden block:

1. Method 1 (Return empty strings):

In this method, we'll make sure to return empty strings from our functions.

<script>
import { toast } from "svelte-sonner";

/**
* @param {number | string} resultsLength
* @returns {string} - Empty string to avoid display issues
*/
function showSuccess (resultsLength) {
toast.success(`${resultsLength} result${resultsLength > 1 ? "s" : ""} retrieved!`)
return ""; // Return an empty string
}

/**
* @param {string} [errorMessage]
* @returns {string} - Empty string to avoid display issues
*/
function showError(errorMessage) {
toast.error(`An Error Occured`, {
message: errorMessage ?? "Unknown Error"
})
return ""; // Return an empty string
}

</script>

{#await data.myPromise}
  <!-- Display this while the promise is pending -->
<Loader />

{:then results}
<!-- Run showSuccess -->
{showSuccess(results.length)} <!-- Won't render any text in the UI -->

<!-- This shows if/when the promise is resolved -->
{#each results as result}
<li>{result}</li>
{/each}

{:catch error}
<!-- Run showError -->
{showError(error.message)} <!-- Won't render any text in the UI -->

<!-- This shows if/when the promise is rejected -->
<p class="text-red">{error?.message ?? "Something went wrong"}</p>
{/await}
Copy after login

This will make sure empty strings are returned.

--- Or ---

2. Method 2 (Hide the returned text from the function in the UI with CSS.)

In this method, we'll hide the function block in the UI instead, so the text returned is hidden from the user's sight.

<script>
import { toast } from "svelte-sonner";

/**
* @param {number | string} resultsLength
*/
function showSuccess (resultsLength) {
toast.success(`${resultsLength} result${resultsLength > 1 ? "s" : ""} retrieved!`)
// No explicit return necessary. Returns undefined by default
}

/**
* @param {string} [errorMessage]
* @returns {string}
*/
function showError(errorMessage) {
toast.error(`An Error Occured`, {
message: errorMessage ?? "Unknown Error"
})
// No explicit return necessary. Returns undefined by default
}

</script>

{#await data.myPromise}
  <!-- Display this while the promise is pending -->
<Loader />

{:then results}
<div class="hidden"> <!-- Hide the function block -->
  <!-- Display results -->

{showSuccess(results.length)}
</div>

<!-- This shows if/when the promise is resolved -->
{#each results as result}
<li>{result}</li>
{/each}

{:catch error}
<div class="hidden"><!-- Hide the function call -->
{showError(error.message)}
<div>

<!-- This shows if/when the promise is rejected -->
<p class="text-red">{error?.message ?? "Something went wrong"}</p>
{/await}

<style>
  .hidden {
    display: none;
  }
</style>
Copy after login

This CSS-based method will make sure that the returned text is hidden from sight.

HappyHacking

PS: Need to employ a SvelteKit Dev? Contact me

The above is the detailed content of Running a Function When an #await Block resolves in Svelte(Kit). For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template