javascript - 获取异步/等待数据并以 html 格式显示/返回

标签 javascript html async-await

我是异步/等待获取的新手。下面是我的 HTML 代码

  <div id="content">
    <!-- Data will appear here as list -->
  </div>

下面是我的 vanilla JS 代码

function loadData() {
  const element = document.getElementById("content");
  element.innerHTML = getTemplate();
}

function getTemplate() {
  async function getPosts() {
    try {
      const url = "https://jsonplaceholder.typicode.com/posts";
      const response = await fetch(url);
      console.log(response);

      if (response.ok) {
        const res = await response.json();
        return res;
      } else {
        throw new Error(response.statusText);
      }
    } catch (error) {
      return error;
    }
  }

  getPosts().then(data => console.log(data));

  //How I return data from here so it will update in the DOM

};

loadData();

如何在使用 vanilla JS 异步/等待获取我的数据后将数据显示为列表。

最佳答案

如果重新组织一下代码没有问题,请尝试以下操作。关于如何返回,请记住异步函数返回一个 promise ,并且您必须在上下文中工作,所以我得到了调用 getPosts 的响应 promise ,并使用数据获得了模板,然后将其提供#内容

function loadData() {
  const element = document.querySelector("div#content");

  getPosts().then(posts => {
    const template = getTemplate(posts);

    element.innerHTML = template;
  });
}

async function getPosts() {
  const url = "https://jsonplaceholder.typicode.com/posts";
  const response = await fetch(url);

  return await response.json();
}

function getTemplate(posts) {
  const rows = posts.map(postToRowView).join("");

  return `<table>
    <thead>
      <tr>
        <th>Title</th>
        <th>Body</th>
      </tr>
    </thead>

    <tbody>${rows}</tbody>
  </table>`;
}

function postToRowView(post) {
  return `<t>
    <td>${post.title}</td>
    <td>${post.body}</td>
  </tr>`;
}

loadData();
<div id="content"></div>

关于javascript - 获取异步/等待数据并以 html 格式显示/返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58360029/

相关文章:

javascript - 在 puppeteer/JavaScript 中重试 page.goto、page.waitForNavigation 等的最佳实践

javascript - Ajax 响应字符串作为函数名称

javascript - 跨浏览器 JavaScript 不工作

html - Html制作的菜单栏,悬停和选择效果

html - CSS:下拉菜单隐藏在内容后面

c# - 寻找一种优雅的方式来绕过 "Cannot await in the body of a finally clause"

javascript - 上传到 Cloudinary API - 文件参数无效

javascript - 下拉值所选值

javascript - 在 Python 中使用 java 脚本抓取网页

html - 如何在带有超链接的 UILabel 上显示 HTML 文本(作为字符串)?