You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取NewsAPI接口返回的Promise中的JSON数据?

如何获取Promise中的异步数据

嘿,我来帮你搞定这个问题!你之所以拿不到数据,是因为response.json()返回的是一个Promise对象,它的结果是异步返回的,不能直接像访问普通对象属性那样去获取里面的值——那些[[promiseValue]]是Promise的内部隐藏属性,根本不允许直接访问哦。

下面给你两种常用的正确做法:

方法1:使用.then()链式调用

既然response.json()返回Promise,那我们可以继续用.then()来接收它resolve后的数据,修改你的代码如下:

fetch(new Request('https://newsapi.org/v2/top-headlines?country=us&apiKey=你的API密钥'))
  .then(function(response) {
    // 这里返回json()的Promise
    return response.json();
  })
  .then(function(data) {
    // 这里的data就是Promise resolve后的实际新闻数据
    console.log(data);
    // 现在你可以正常访问数据里的属性,比如articles列表
    console.log(data.articles);
  })
  .catch(function(error) {
    // 别忘了处理请求失败的情况
    console.error('请求出错:', error);
  });

方法2:使用async/await语法(更简洁)

如果你的代码在async函数里,可以用await来等待Promise完成,代码看起来更像同步逻辑:

async function fetchNews() {
  try {
    const response = await fetch(new Request('https://newsapi.org/v2/top-headlines?country=us&apiKey=你的API密钥'));
    const data = await response.json(); // 等待json()的Promise完成,直接拿到数据
    console.log(data);
    console.log(data.articles);
  } catch (error) {
    console.error('请求出错:', error);
  }
}

// 调用函数
fetchNews();

简单总结一下:Promise的结果必须通过它的异步回调(.then())或者await来获取,这是异步编程的核心规则,直接访问内部属性是行不通的哦。

内容的提问来源于stack exchange,提问作者user2301515

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:54:19