为何`response.json().results`返回undefined值?
为什么fetch中直接访问
response.json().results会返回undefined? 核心原因很简单:response.json()返回的是一个Promise对象,不是立刻就能拿到的JSON解析结果。
错误代码的问题
你第一段代码里,直接写return response.json().results,相当于在访问Promise对象的results属性——但Promise本身根本没有这个属性,所以返回undefined,这个值被传到下一个then里,自然打印出来就是undefined。
错误代码示例:
const URLS = "https://pokeapi.co/api/v2/pokemon?limit=1000" fetch(URLS) .then(response => { return response.json().results // Promise对象没有results属性,返回undefined }) .then((pokemons) => { console.log(typeof pokemons) // 输出undefined });
正确代码的逻辑
第二段代码里,你返回了response.json()这个Promise,当浏览器完成JSON解析后,会把解析好的JavaScript对象传递给下一个then的回调参数pokemons。这时候pokemons是真正的API响应对象,自然能访问到它的results属性。
正确代码示例:
const URLS = "https://pokeapi.co/api/v2/pokemon?limit=1000" fetch(URLS) .then(response => { return response.json() // 返回Promise,等待解析完成 }) .then((pokemons) => { console.log(typeof pokemons.results) // 输出"object",因为results是数组 });
更直观的写法(async/await)
如果用async/await语法,这个异步流程会更清晰,能明确看到response.json()需要等待才能拿到结果:
const URLS = "https://pokeapi.co/api/v2/pokemon?limit=1000"; async function fetchPokemons() { const response = await fetch(URLS); const pokemonData = await response.json(); // 必须await等待解析完成 console.log(typeof pokemonData.results); } fetchPokemons();
内容的提问来源于stack exchange,提问作者Ahmed Gaber
相关产品推荐
相关产品推荐

