如何根据“fetch”结果创建“li”

Cha*_*Teh 1 javascript

我试图通过参考https://dog.ceo/dog-api/documentation/上的文档从该网站提取一些数据

我正在尝试检索狗品种列表并创建一个列表。我正在使用 javaScript 的“fetch”

let dog_list = [];
fetch('https://dog.ceo/api/breeds/list/all')
  .then(response => {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error(response.statusText);
    }
  })
  .then(data => dog_list = data.message)
const container = document.getElementById("container");
for (dog in dog_list) {
  let li = document.createElement("li");
  let node = document.createTextNode(dog);
  li.appendChild(node);
  container.appendChild(li);
}
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Dog Breed List</title>
</head>

<body>
  <ul id="container"></ul>
  <script src="dog_breed.js"></script>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

我在第二个“then”遇到问题,我不知道如何将 json 对象转换为数组并将其显示为

  • 狗1
  • 狗2
  • 狗3

Mil*_*lan 5

li只需在创建dog_list 的回调中构建您...

像这样的东西...

let dog_list = [];
const container = document.getElementById("container");
fetch('https://dog.ceo/api/breeds/list/all')
    .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error(response.statusText);
        }
    })
    .then(data => {
        dog_list = data.message;
        for (dog in dog_list) {
            let li = document.createElement("li");
            let node = document.createTextNode(dog);
            li.appendChild(node);
            container.appendChild(li);
        }
    });

Run Code Online (Sandbox Code Playgroud)

为什么需要在 Promise 处理程序中构建生成的 DOM 结构?

因为完整的 块将异步fetch(/*...*/).then(/*...*/).then(/*...*)执行

无需等待该代码完成,主线(“全局”)代码将从之后的行继续执行,在您的情况下,这是获取容器并开始添加li元素。问题是,此时对 fetch 调用的响应的处理甚至不会开始(即使 fetch 已被执行并且结果已返回),因此dog_list将为空。