javascript - 为什么 `response.json().<key>` 返回无法识别的值

标签 javascript json

我正在尝试通过下面代码中的 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 函数中的 .thenawait 等待 Promise,则无法直接访问该结果的属性。

关于javascript - 为什么 `response.json().<key>` 返回无法识别的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75240286/

相关文章:

javascript 在设置 document.body.innerHTML 时无效

javascript - 输入在此代码中添加标记样式的位置(传单)

jquery - 如何使用 jquery 将多个 json 格式的参数传递给 Web 服务?

c# - 在 C# 中解析来自 json 的数据

json - 如何使用 AngularJS 从其他域加载 JSON 数据对象(无回调函数)

javascript - jquery 移动 openlayer 搜索

javascript - 函数组合和偏应用的直观思考方式

javascript - 将文件从 Electron 发送到连接在 LAN 中的服务器

javascript - 在 IE7 中模拟 localStorage 的问题

java - 我如何反序列化字符串 Json Date?