获取返回Promise状态:pending

Sté*_* R. 8 javascript json ecmascript-6 fetch-api

我使用jsonplaceholder URL测试fetch API,但我的函数返回"Promise State:Pending",我不明白为什么:

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

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

users.then(response => {
  console.log(response.text());
});
Run Code Online (Sandbox Code Playgroud)

我认为问题是因为异步/同步方法?

T.J*_*der 9

我认为问题变成异步/同步方法?

是.你(大部分)正确地消耗了原始的fetch()承诺,但返回了承诺.所以:text()

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

在上面的#3,我们通过对它做一些事情来处理来自原始fetch()text()承诺的错误.

务必处理承诺拒绝.如果你不这样做,那么它们与未处理的异常不同.它们被报告给控制台,并且某些环境(如最新版本的Node)终止未处理的拒绝.


由于您正在请求JSON,因此您可能希望使用json()而不是text()读取和解析它:

users.then(response => response.json())
     .then(arrayOfUsers => {
          console.log(arrayOfUsers);
     })
     .catch(error => {
          // handle error
     });
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)