Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
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?