我刚刚开始学习 Fetch API:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
这是我编写的代码片段,用于修改它:
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 对象。
类似于使用 JSON.parse() 时得到的结果。
相反,我得到了一个承诺对象。
如果我像这里所示扩大承诺链......
return response.json().then(function(json) {
// process your JSON further
});
...然后它就起作用了:在以下 Promise 的 then 方法中,它显示为 json。
为什么我无法在第一个 Promise 的 then() 中检索 JSON 数据?
谁能解释一下这里发生了什么吗?
我真的非常感激。
因为response.json()返回另一个promise(它在你的函数体内)
https://developer.mozilla.org/en-US/docs/Web/API/Body/json https://developer.mozilla.org/en-US/docs/Web/API/Body/json
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)