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

Node.js中遍历PostgreSQL查询Promise结果并校验双表数据后更新表的方法

核心思路

你当前拿到的promiseresult是按「员工1员工表结果、员工1部门表结果、员工2员工表结果、员工2部门表结果……」的顺序两两成对存储的,你可以直接按步长2遍历校验,也可以调整代码先对同员工的查询结果做分组,逻辑更清晰易维护。


方案1:优化原有代码逻辑(更推荐,可维护性更高)

把同个员工的两次查询打包成一组,结果天然分组,不需要手动计算索引匹配:

const result = await DBService.query(EmpQuery.getEmployeeId());

// 每个员工对应一个Promise,返回值包含该员工的两次查询结果
const empGroupPromises = result.rows.map(async empAccount => {
  try {
    const empId = empAccount.empid;
    const QueryObj = new EmpQuery(empId);
    const empRes = await DBService.query(QueryObj.getCurrentEmployee());
    const deptRes = await DBService.query(QueryObj.getEmployeeWithDept());
    return { empRes, deptRes, empId };
  } catch (error) {
    logger.info(error);
    return null; // 出错项直接返回空,后续过滤即可
  }
});

const empResultList = await Promise.all(empGroupPromises);

// 遍历校验+执行更新
for (const item of empResultList) {
  if (!item) continue; // 跳过查询出错的项
  const { empRes, deptRes, empId } = item;
  // PostgreSQL查询有效判断标准默认是返回的rows数组长度大于0,可根据业务调整规则
  const isEmpValid = empRes?.rows?.length > 0;
  const isDeptValid = deptRes?.rows?.length > 0;
  if (isEmpValid && isDeptValid) {
    // 两次查询均有效,执行你的更新逻辑
    // 示例:await DBService.query(更新SQL语句, [empId, 其他参数])
  }
}

方案2:不改原有逻辑,直接处理现有promiseresult

如果不想调整之前生成empPromises的代码,可以直接按步长2遍历结果数组:

const promiseresult = await Promise.all(empPromises);

// 步长为2遍历,每两个元素对应一个员工的两次查询结果
for (let i = 0; i < promiseresult.length; i += 2) {
  const empRes = promiseresult[i]; // 第i位为当前员工的员工表查询结果
  const deptRes = promiseresult[i + 1]; // 第i+1位为当前员工的部门表查询结果
  // 校验规则和方案1一致
  const isEmpValid = empRes?.rows?.length > 0;
  const isDeptValid = deptRes?.rows?.length > 0;
  if (isEmpValid && isDeptValid) {
    // 执行更新操作
  }
}

补充说明

如果业务中对「有效数据」的判断除了返回结果非空,还要求特定字段不为空、符合特定取值范围等,可以直接在校验条件中补充对应判断规则即可。如果更新操作需要批量并行执行,可以把符合条件的更新Promise收集到数组中,最后统一用Promise.all执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:36:05