簡體   English   中英

fetch 函數返回 Promise<pending>

[英]fetch function return Promise <pending>

所以我這里的代碼返回一個 Promise 並且因為我使用then語法我不知道為什么會發生這種情況:-??

fetch('someurltoAJsonFile.json')
  .then(function(response) {
    console.log(response.json());});

node-fetch 庫中的 response.json() 也返回一個承諾,而不是嘗試

fetch('someurltoAJsonFile.json')
  .then(response => response.json())
  .then(data => {
    console.log(data)
  });

您可以在此處查看有關它的更多詳細信息

編輯:

似乎返回的響應不在有效的 json 中,因此為了完整起見,這里是文本代碼

fetch('someurltoAJsonFile.json')
  .then(response => response.text())
  .then(data => {
    console.log(data)
  });

給出的函數then參數將被異步執行(在某個時候,當你的服務器返回的響應未來),但then自己立即返回承諾(以同步方式),其定義

如果您希望代碼看起來不那么嵌套(更多是同步代碼),您可以使用 await 但您必須使用 async 函數使整個代碼不透明

async function load() 
{
  let response = await fetch('someurltoAJsonFile.json');
  let data = await response.json();
  console.log(data);
}

爭論這是否有資格作為答案,但我今天遇到了類似的情況,導致我提出這個問題,即使我的問題最終與環境有關。

如果您看到 promise 未決並且您的代碼是正確的,並且您花了太多時間試圖找出 console.log 未顯示的原因,請仔細檢查您是否在 chrome 的開發工具中打開了“信息”。 我只打開了警告,所以我沒有看到我的 console.log。

這段代碼有效並展示了一種很好的方式來獲取並獲得承諾,而不會出現未決問題。

如果您有 cors 問題,請在您的服務器中運行此代碼在谷歌瀏覽器中下載此擴展程序“允許 CORS:訪問控制允許來源”

 async function invoices() { let response = await fetch('https://blockchain.info/latestblock?utm_medium=referral&utm_campaign=ZEEF&utm_source=https%3A%2F%2Fjson-datasets.zeef.com%2Fjdorfman'); let data = await response.json(); console.log(data); return data; } invoices().then(data => { console.log(data); });

暫無
暫無

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

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