我正在尝试通过下面代码中的 api 获取 json 文件,当我将 json 响应转换为 javascript 对象时,我希望能够访问 results
中的键 results
的值该对象是一个数组,但是当我在第二个然后链中记录响应时,我得到未识别
const URLS = "https://pokeapi.co/api/v2/pokemon?limit=1000"
fetch(URLS)
.then(response => {
return response.json().results
})
.then((pokemons) => {
console.log(typeof pokemons)
});
当我将代码更改为这样时
const URLS = "https://pokeapi.co/api/v2/pokemon?limit=1000"
fetch(URLS)
.then(response => {
return response.json()
})
.then((pokemons) => {
console.log(typeof pokemons.results)
});
看起来工作正常,但我不明白为什么会发生这个问题
最佳答案
response.json()
返回一个 Promise
,解析将响应文本解析为 JSON 的结果。如果不使用 async
函数中的 .then
或 await
等待 Promise,则无法直接访问该结果的属性。
关于javascript - 为什么 `response.json().<key>` 返回无法识别的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75240286/