【问题标题】:fetch return Promise state: pending获取返回承诺状态:待定
【发布时间】:2017-09-18 07:05:52
【问题描述】:

我用 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());
});

我认为问题出在异步/同步方法上?

【问题讨论】:

    标签: javascript json ecmascript-6 fetch-api


    【解决方案1】:

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

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

    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);
    }

    【讨论】:

    • 谢谢 Crowder :) 我已将 .text() 替换为 .json()。也感谢承诺拒绝!
    • 我有最后一个问题:为什么 JSON.parse(response) 不起作用?我必须使用 .json() 吗?
    • @StéphaneR.: response 不是一个字符串,它是一个object,它可以让您获取有关响应的各种信息(包括标题、状态等)。当收到足够多的响应以向您提供有用的信息时,您就会收到它,这可能是在收到响应的整个正文之前。这就是为什么 text()json() 以及这样的返回承诺,因为他们需要阅读整个响应正文。
    • 非常感谢您的解释,我明白了!祝你有美好的一天.. :)
    猜你喜欢
    • 1970-01-01
    • 2018-09-10
    • 2021-03-01
    • 2020-12-18
    • 2017-02-07
    • 1970-01-01
    • 2021-07-22
    • 2020-12-20
    相关资源
    最近更新 更多