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

基于双JSON文件与.then方法的result获取逻辑问题求助

解决异步请求JSON的逻辑问题

方案1:用async/await写(更清晰好懂)

直接用async函数包裹逻辑,await处理异步请求,避免.then嵌套混乱:

async function getTargetData(hovered) {
  let result;
  // 判断hovered是否为空
  if (!hovered) {
    // 请求morework.json并筛选含images的项
    const moreworkData = await fetch('morework.json').then(res => res.json());
    result = moreworkData.filter(item => item.images);
  } else {
    // 请求home.json并筛选uid包含hovered的项
    const homeData = await fetch('home.json').then(res => res.json());
    result = homeData.filter(item => item.uid.includes(hovered));
  }
  // 这里处理最终结果,比如渲染页面
  console.log(result);
  return result;
}

// 调用函数,传入当前hovered值
getTargetData(hovered);

方案2:用.then链式调用(严格基于Promise)

如果非要用.then,得把两个分支的Promise链分开,别让逻辑互相覆盖:

function getTargetData(hovered) {
  let dataPromise;
  if (!hovered) {
    dataPromise = fetch('morework.json')
      .then(res => res.json())
      .then(data => data.filter(item => item.images));
  } else {
    dataPromise = fetch('home.json')
      .then(res => res.json())
      .then(data => data.filter(item => item.uid.includes(hovered)));
  }
  
  // 统一处理结果或错误
  dataPromise
    .then(result => {
      console.log(result);
      // 这里写渲染逻辑
    })
    .catch(err => {
      console.error('数据拉取失败:', err);
    });
}

// 调用函数
getTargetData(hovered);

额外注意事项

  • 确认hovered的判断逻辑:如果hovered可能是空字符串、null或undefined,!hovered能覆盖这些情况,要是有特殊需求(比如0不算空),得调整判断条件
  • 一定要加.catch()捕获错误,不然请求失败时控制台只会报错,不好排查问题
  • 如果home.json是提前加载好的全局数据,else分支里不用重新请求,直接用已有的数据筛选就行,能提升性能:
// 假设homeData已经是全局变量或提前加载完成
async function getTargetData(hovered) {
  let result;
  if (!hovered) {
    const moreworkData = await fetch('morework.json').then(res => res.json());
    result = moreworkData.filter(item => item.images);
  } else {
    result = homeData.filter(item => item.uid.includes(hovered));
  }
  console.log(result);
  return result;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 07:13:10