JavaScript fetch API - 为什么 response.json() 返回一个 promise 对象(而不是 JSON)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39435842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript fetch API - Why does response.json() return a promise object (instead of JSON)?
提问by michael.zech
I've just started to learn the Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
我刚开始学习 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}
});
I would have expected to get an JSON object out of response.json().
我本来希望从 response.json() 中得到一个 JSON 对象。
Similar to what you get when using JSON.parse().
类似于使用 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 it works: Within the then method of the following promise it appears as json.
...然后它起作用了:在以下承诺的 then 方法中,它显示为 json。
Why can't I retrieve the JSON data within the then() of the first promise?
为什么我不能在第一个承诺的 then() 中检索 JSON 数据?
Can anyone please explain what is going on here?
谁能解释一下这里发生了什么?
I would really much appreciate it.
我真的很感激。
采纳答案by dee zg
because response.json() returns another promise (which is within your function body)
因为 response.json() 返回另一个承诺(在你的函数体内)