You need to enable JavaScript to run this app. 如何同时将两个不同endpoint的JSON数据作为同一函数的入参?
优惠活动
大模型
产品
解决方案
定价
更多

如何同时将两个不同endpoint的JSON数据作为同一函数的入参?

解决方案

核心是使用Promise.all处理并发异步请求,等待两个接口都返回并解析完成后,再按顺序将两份数据传入目标函数。

推荐写法(async/await,可读性更高)

function otherFunc(jsonData1, jsonData2){
  // 原有业务逻辑
}

async function getJsonData(url1,url2){
  // 并发发起两个请求,全部完成后拿到响应对象数组
  const [res1, res2] = await Promise.all([
    fetch(url1),
    fetch(url2)
  ])
  // 并发解析两个响应为JSON格式
  const [data1, data2] = await Promise.all([
    res1.json(),
    res2.json()
  ])
  // 传入两份数据到目标函数
  otherFunc(data1, data2)
}

getJsonData(someUrl1, someOtherUrl2)

传统.then链式写法

function otherFunc(jsonData1, jsonData2){
  // 原有业务逻辑
}

function getJsonData(url1,url2){
  Promise.all([fetch(url1), fetch(url2)])
    .then(([res1, res2]) => Promise.all([res1.json(), res2.json()]))
    .then(([data1, data2]) => otherFunc(data1, data2))
    .catch(err => {
      // 统一捕获请求、解析阶段的异常
      console.error('数据拉取失败:', err)
    })
}

getJsonData(someUrl1, someOtherUrl2)

补充说明

  • Promise.all返回的结果数组顺序和传入的请求顺序完全一致,不会受接口返回速度影响
  • 如果需要兼容单个请求失败的场景,可将Promise.all替换为Promise.allSettled,自行判断每个请求的成功/失败状态后再做处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 18:45:03