获取函数 return 承诺 <pending>

fetch function return Promise <pending>

所以我的代码 return 是一个 Promise,因为我使用的是 then 语法,所以我不知道为什么会这样 :-??

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

作为then参数给出的函数将异步执行(将来某个时候当你的服务器return响应时),但then本身return立即承诺(以同步方式)通过其 definition

如果你想让代码看起来不那么嵌套(更多的是同步代码)你可以使用 await 但你必须使用异步函数使整个代码不透明

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

response.json() 在 node-fetch 库中也是 returns 一个承诺,而不是尝试

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

您可以查看更多详细信息here

编辑:

似乎返回的响应不在有效 json 中,因此为了完整起见,这里有一个文本代码

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

争论这是否符合答案的条件,但我 运行 今天遇到了类似的情况,这导致我提出了这个问题,尽管我的问题最终与环境有关。

如果您看到 promise pending 并且您的代码是正确的,并且您花了太多时间试图找出 console.log 未显示的原因,请仔细检查您是否已 "Info"在 chrome 的开发工具中。我只打开了警告,所以我没有看到我的 console.log.

此代码有效并展示了一种在没有未决问题的情况下进行获取和获得承诺的好方法。

运行 如果您有 cors 问题,请在您的服务器中下载此扩展 google chrome "Allow CORS: Access-Control-Allow-Origin"

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