获取 response.text() returns 未决承诺

fetch response.text() returns pending promise

我用 jsonplaceholder URL 测试了提取 API,但是我的函数 returns "Promise State: Pending",我不明白为什么:

function getUsers(url) {
  return fetch(url)
}

const users = getUsers(`https://jsonplaceholder.typicode.com/users`);

users.then(response => {
  console.log(response.text());
});

我认为问题是因为 asynchronous/synchronous 方法?

I think the problem become asynchrone/synchrone method ?

是的。您(大部分)正确地使用了原始的 fetch() 承诺,但 text() returns 承诺。所以:

users.then(response => response.text()) // 1
     .then(json => {                    // 2
          console.log(json);
     })
     .catch(error => {                  // 3
          // handle error
     });

fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.text())      // 1
     .then(json => {                    // 2
          log("typeof json: " + typeof json);
          log(json);
     })
     .catch(error => {                  // 3
          // handle error
     });

function log(msg) {
  var p = document.createElement("pre");
  p.appendChild(document.createTextNode(msg));
  document.body.appendChild(p);
}

在上面的 #1 中,我们通过开始阅读正文的过程来响应 fetch() 承诺的成功解决,返回来自 text() 的承诺。

在上面的 #2 中,我们通过使用生成的文本(包含 JSON 的字符串)来响应 text() 的承诺的成功解决。

在上面的第 3 条中,我们通过处理来自原始 fetch()text() 承诺的错误来处理它。

始终确保处理拒绝承诺。如果不这样做,它们就不同于未处理的异常。它们会报告给控制台,并且某些环境(如最新版本的 Node)会因未处理的拒绝而终止。


由于您请求的是 JSON,您可能希望使用 json() 而不是 text(),因此您既要阅读又要解析它:

users.then(response => response.json())
     .then(arrayOfUsers => {
          console.log(arrayOfUsers);
     })
     .catch(error => {
          // handle error
     });

fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
     .then(arrayOfUsers => {
          log("typeof arrayOfUsers: " + typeof arrayOfUsers);
          log("arrayOfUsers.length: " + arrayOfUsers.length);
     })
     .catch(error => {                  // 3
          // handle error
     });

function log(msg) {
  var p = document.createElement("pre");
  p.appendChild(document.createTextNode(msg));
  document.body.appendChild(p);
}