4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SvelteのAwait blocksを使ってみる

Last updated at Posted at 2020-09-04

はじめに

Web APIでデータを取得する際にfetch APIだけを使っていたのですが、
.thenが何回も出て見通しが悪くなったので、async/awaitとSvelteのAwaite blocksで見通しをよくする。

元のコード

<script>
  let items;
	
  $: fetch('https:...')
    .then(res => res.json())
    .then(data => {
      items = data;
    });
</script>

{#if items}
  {#each items as item}
    <p>{item.name}</p>

  {/each}
{:else}
  <p>ロード中</p>
{/if}

async/await Await blocks

<script>	
  const fetchItems = async function() {
    const items = await fetch('https:...');
    return await items.json();
  }
</script>

{#await fetchItems()}
  <p>ロード中</p>
{:then items}
  {#each items as item}
    <p>{item.name}</p>
  {/each}
{/await}

async/awaitの方が見易くていいですね。
それにAwait blocksに{:catch error}を使うとエラー時の分岐も簡単に使えるのでこっちを普段から使う方がよさそう。

参考記事

Logic / Await blocks • Svelte Tutorial

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?