zoukankan      html  css  js  c++  java
  • [Svelte 3] Use await block to wait for a promise and handle loading state in Svelte 3

    Most web applications have to deal with asynchronous data at some point.

    Svelte 3 apps are no different, luckily Svelte allows us to await the value of a promise directly in markup using await block.

    In this lesson we're going to learn how to use the await block to fetch the data from a Star Wars API and both display the data and handle loading state.

    // Before:
    
    <script>
      async function getRandomStarWarsCharacter() {
        const randomNumber = Math.floor(Math.random() * 10) + 1;
        const apiResponse = await fetch(
          `https://swapi.co/api/people/${randomNumber}/`
        );
    
        return await apiResponse.json();
      }
    
      let character;
      getRandomStarWarsCharacter().then(value => (character = value));
    </script>
    
    <h1>{!character ? 'Loading ...' : character.name}</h1> 
    // After:
    <script>
      async function getRandomStarWarsCharacter() {
        const randomNumber = Math.floor(Math.random() * 10) + 1;
        const apiResponse = await fetch(
          `https://swapi.co/api/people/${randomNumber}/`
        );
    
        return await apiResponse.json();
      }
    
      let promise = getRandomStarWarsCharacter();
    </script>
    
    <!-- <h1>{!character ? 'Loading ...' : character.name}</h1> -->
    
    {#await promise}
      <h1>Loading...</h1>
    {:then character}
      <h1>{character.name}</h1>
    {/await}
  • 相关阅读:
    用函数装饰一首诗
    [转]最常用的15大Eclipse开发快捷键技巧
    [转]python 模块 chardet下载及介绍
    python手动设置递归调用深度
    view-xpath
    开源项目的贡献流程
    MIT许可证
    scrapy分布式的几个重点问题
    【bzoj1026】[SCOI2009]windy数 数位dp
    【bzoj5064】B-number 数位dp
  • 原文地址:https://www.cnblogs.com/Answer1215/p/11631457.html
Copyright © 2011-2022 走看看