【问题标题】:How to get fetched data to show on HTML如何获取要在 HTML 上显示的数据
【发布时间】:2021-06-11 10:46:35
【问题描述】:

我正在浏览 Coding Train 视频,并通过从 Poemist API 获取数据来尝试我自己的看法。我可以从 API 中获取诗歌的标题以显示在控制台中;但是,我无法让它显示在 HTML 上(它只是显示未定义)。有人知道我在这里可能做错了什么吗?下面是我的代码。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Fetch a poem</title>
  </head>
  <body>
    <h1>Fetch a Poem</h1>
    <p id="poem">title</p>
    <script>
      console.log('about to fetch a poem');
      catchPoem()
        .then(poem => {
          document.getElementById('poem').innerText = poem;
          console.log('yay');
        })
        .catch(error => {
          console.log('error!');
          console.error(error);
        });

      async function catchPoem() {
        const response = await fetch('https://www.poemist.com/api/v1/randompoems');
        let json = await response.json();
        let title = json[0].title
        console.log(title);
      }
    </script>
  </body>
</html>

【问题讨论】:

  • 你在 catchPoem 中什么都不返回,所以你在 then 中没有定义

标签: javascript async-await fetch


【解决方案1】:
async function catchPoem() {
    const response = await fetch('https://www.poemist.com/api/v1/randompoems');
    let json = await response.json();
    let title = json[0].title
    // console.log(title);
    return title;
}

【讨论】:

    【解决方案2】:

    你没有从函数catchPoem 返回任何东西,这就是你得到undefined 的原因。你只需要从函数中返回title

    if (title) {
        return title;
      }
    

    console.log('about to fetch a poem');
    
    catchPoem()
      .then(poem => {
        document.getElementById('poem').innerText = poem;
        console.log('yay');
      })
      .catch(error => {
        console.log('error!');
        console.error(error);
      });
    
    async function catchPoem() {
      const response = await fetch('https://www.poemist.com/api/v1/randompoems');
      let json = await response.json();
      let title = json[0].title
      console.log(title);
      if (title) {
        return title
      }
    }
    <h1>Fetch a Poem</h1>
    <p id="poem">title</p>

    【讨论】:

    • catchPoem 是异步函数,所以不需要使用 Promise.resolve,直接返回结果
    • 我多么愚蠢。我没看到。感谢您的捕获...
    猜你喜欢
    • 2021-06-06
    • 1970-01-01
    • 2018-04-03
    • 2018-06-17
    • 1970-01-01
    • 2016-07-20
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多