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

Javascript遍历数组逐个传值调用查询,Promise实现无法单独取项如何解决

问题原因
  • 你当前代码中遍历items时,传给查询方法的还是完整的items数组,没有用到当前遍历项的Codes字段值
  • Codes本身是嵌套的字符串数组,你需要再遍历一层才能拿到单个code值传入查询
实现方案

方案1:并行发起所有查询(性能更高,适合无请求频率限制的场景)

先把所有嵌套的code平铺为一维数组,再批量发起查询,全部完成后统一返回结果:

const getByCodes = async ({ neo4j }, { items }) => {
  // 平铺所有code为一维数组
  const allSingleCodes = items.flatMap(item => item.Codes);
  return Promise.all(
    allSingleCodes.map(async singleCode => {
      // 传入单个code调用查询,参数名根据你实际查询方法要求调整即可
      return neo4j.run(CodesQuery.getCodesQuery({ code: singleCode }))
    })
  )
}

方案2:串行逐个发起查询(适合有请求频率限制,需要控制调用速度的场景)

const getByCodes = async ({ neo4j }, { items }) => {
  const allSingleCodes = items.flatMap(item => item.Codes);
  const queryResults = [];
  for (const code of allSingleCodes) {
    const res = await neo4j.run(CodesQuery.getCodesQuery({ code }));
    queryResults.push(res);
  }
  return queryResults;
}

可选:按原items分组返回结果

如果需要保留原items的结构,每个元素对应自己的Codes查询结果,可以用嵌套写法:

const getByCodes = async ({ neo4j }, { items }) => {
  return Promise.all(
    items.map(async item => {
      const itemCodeResults = await Promise.all(
        item.Codes.map(code => neo4j.run(CodesQuery.getCodesQuery({ code })))
      )
      return {
        ...item,
        queryResults: itemCodeResults
      }
    })
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:24:06