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

JavaScript中如何访问Promise返回的数组

访问async函数返回的数组值

你的getFilteredResults是异步函数,它的返回值会被自动包装成Promise,所以直接打印会看到Promise {<pending>}——这是正常现象,因为异步操作需要时间完成,Promise会先返回,等操作完成后进入fulfilled状态并携带最终的数组结果。

要访问数组里的值,有两种常用方式:

方式一:使用await(需在async函数内调用)

await会等待Promise完成,直接返回最终的数组结果,示例:

// 定义一个async函数来调用你的异步函数
async function handleResults() {
  // 传入对应的weather、type、activity参数
  const filteredArray = await getFilteredResults("温暖", "城市", "观光");
  // 现在filteredArray就是你要的数组
  console.log(filteredArray);
  
  // 访问数组第一个元素的属性,比如HotelName
  if (filteredArray.length > 0) {
    console.log(filteredArray[0].HotelName); // 输出'Desert Dreams'
    console.log(filteredArray[0].City); // 输出'Dubai'
  }
}

// 调用这个函数
handleResults();

方式二:使用.then()链式调用

如果不想额外写async函数,可以用Promise的.then()方法,在Promise完成后处理结果:

getFilteredResults("温暖", "城市", "观光")
  .then(filteredArray => {
    console.log(filteredArray);
    if (filteredArray.length > 0) {
      console.log(filteredArray[0].HotelName); // 输出'Desert Dreams'
    }
  })
  .catch(err => {
    // 处理可能的错误(比如fetch失败、JSON解析错误)
    console.error("获取数据出错:", err);
  });

控制台直接测试技巧

如果在浏览器控制台直接测试,可以直接用await调用,无需包裹async函数:

const results = await getFilteredResults("温暖", "城市", "观光");
console.log(results[0].HotelName);

注意:如果返回的数组可能为空,访问results[0]前最好先判断filteredArray.length > 0,避免出现Cannot read properties of undefined的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:33:13