JavaScript fetch API - 为什么response.json()返回一个promise对象(而不是JSON)? [英] JavaScript fetch API - Why does response.json() return a promise object (instead of JSON)?

查看:555
本文介绍了JavaScript fetch API - 为什么response.json()返回一个promise对象(而不是JSON)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习Fetch API: https ://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

I've just started to learn the Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

这是我写给修补匠的代码片段围绕它:

Here's a code snippet which I wrote to tinker around with it:

fetch('http://swapi.co/api/people/1')
  .then(function(response) {
    var json = response.json();

    console.log(json);
    // Expected : { "name": "Luke Skywalker","height": "1.72 m", ... } 
    // Get : Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
  }); 

我原本希望从response.json()中获取一个JSON对象。

I would have expected to get an JSON object out of response.json().

类似于使用JSON.parse()时获得的内容。

Similar to what you get when using JSON.parse().

相反,我得到一个承诺对象。

Instead I get a promise object.

如果我放大了这里显示的承诺链......

If I enlarge the promise chain like shown here ...

return response.json().then(function(json) {
      // process your JSON further
});

...然后它可以工作:在以下承诺的then方法中,它显示为json。

... then it works: Within the then method of the following promise it appears as json.

为什么我不能在第一个承诺的then()中检索JSON数据?

任何人都可以解释一下这里发生了什么吗?

Can anyone please explain what is going on here?

我真的很感激。

推荐答案

因为response.json()返回另一个promise(在你的函数体内)

because response.json() returns another promise (which is within your function body)

https://developer.mozilla.org/en-US/docs/Web/API/Body / json

这篇关于JavaScript fetch API - 为什么response.json()返回一个promise对象(而不是JSON)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆