簡體   English   中英

獲取返回Promise狀態:pending

[英]fetch return Promise state: pending

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

我認為問題是因為異步/同步方法?

我認為問題變成異步/同步方法?

是。 你(大部分)正確地使用了原始的fetch() promise,但是text() 返回了一個promise。 所以:

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中,我們通過啟動讀取正文文本的過程,從text()返回promise來響應fetch() promise的成功解析。

在上面的#2中,我們通過使用結果文本(包含JSON的字符串text()來響應text()的承諾的成功解決。

在上面的#3中,我們通過對它執行某些操作來處理來自原始fetch()text() promise的錯誤。

務必處理承諾拒絕。 如果你不這樣做,那么它們與未處理的異常不同。 它們被報告給控制台,並且某些環境(如最新版本的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); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM