Complete the code to create a promise that resolves after 2 seconds.
const dataPromise = new Promise((resolve) => {
setTimeout(() => {
resolve([1]);
}, 2000);
});The promise resolves with the string 'Data loaded' after 2 seconds.
Complete the code to await the promise and store the result in a variable.
async function loadData() {
const result = await [1];
return result;
}We await the previously created dataPromise to get the resolved data.
Fix the error in the Svelte component to show loading text while waiting for the promise.
<script>
let data = null;
let loading = true;
dataPromise.then(value => {
data = value;
[1] = false;
});
</script>
{#if loading}
<p>Loading...</p>
{:else}
<p>{data}</p>
{/if}We set loading to false after the promise resolves to update the UI.
Fill both blanks to create a reactive statement that updates when the promise resolves.
<script> let data = null; let loading = true; $: [1] = loading ? 'Loading...' : data; dataPromise.then(value => { data = value; [2] = false; }); </script>
The reactive variable displayText shows loading or data based on loading.
Fill all three blanks to create a Svelte component that streams data chunks and updates the UI.
<script> import { onMount } from 'svelte'; let chunks = []; let loading = true; async function streamData() { const response = await fetch('/stream'); const reader = response.body.getReader(); while(true) { const { done, value } = await reader.read(); if(done) break; chunks = [...chunks, new TextDecoder().[1](value)]; } [2] = false; } onMount(() => { [3](); }); </script> {#if loading} <p>Loading stream...</p> {:else} <p>{chunks.join('')}</p> {/if}
The decode method converts bytes to text, loading is set false after streaming, and streamData is called on mount.