Promesas

PHOTO EMBED

Mon May 27 2024 03:07:54 GMT+0000 (Coordinated Universal Time)

Saved by @davelauren #javascript #svelte

<script>
  async function harryPotterStudents() {
      const res = await fetch('https://hp-api.herokuapp.com/api/characters/students');
      const json = await res.json()

      if (res.ok) {
          return json
      } else {
          throw new Error(json)
      }
  }

  let promise = harryPotterStudents()
</script>

<h2>Estudiantes de la saga Harry Potter (promesas)</h2>
{#await promise}
  <p>Esperando resultados...</p>
{:then students}
  <p>Total estudiantes: {students.length}</p>
  {#each students as {name: alt, house, image: src}}
    {#if src}
      <h3>{alt} ({house})</h3>
      <img height="100" {src} {alt} />
    {/if}
  {/each}
{:catch error}
  <p style="color: red">{error.message}</p>
{/await}
content_copyCOPY