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

Promise中Update数据库查询未执行问题求助

Promise中Update查询未执行的问题排查与解决

核心问题分析

你的代码存在三个关键问题导致Update查询未生效:

  1. Update Promise提前执行:定义insertcctblintblbotagents时直接用了await,导致这个Promise在代码初始化阶段就已经执行,而非等到Promise链的对应阶段才触发,此时ctx.session中的参数可能还没被前面的步骤正确赋值。
  2. SQL表名错误:Update语句的WHERE子句中表名写成了db.agentstoadd,正确表名应为db.tblagentstoadd,导致数据库无法匹配到要更新的行,即使执行了也不会修改数据。
  3. 缺少错误捕获:整个Promise链没有全局异常捕获,即使Update过程报错也无法察觉,误以为代码没执行。

修复步骤与代码示例

1. 修正Update Promise的定义

将其改为返回Promise的函数,确保在需要时才执行:

// 定义为函数,避免提前执行
const insertcctblintblbotagents = () => new Promise((resolve, reject) => {
  // 修正WHERE子句的表名错误
  const sql = 'UPDATE db.tblagentstoadd SET db.tblagentstoadd.ccAgentID = ? WHERE db.tblagentstoadd.AgentID = ?;';
  DB.query(sql, [ctx.session.AgentID, ctx.session.tempAgentID], function(err, result) {
    if (err) {
      console.error('Update操作出错:', err); // 打印错误便于排查
      return reject(err);
    }
    console.log('Update执行结果:', result); // 查看影响行数,确认是否命中行
    return resolve(result);
  })
});

2. 调整Promise链调用方式

在链中调用上述函数,确保Update在正确时机执行,并添加全局错误捕获:

await insertbotagentstoadd
  .then(() => {
    console.log("done with one");
  })
  .then(() => selectbotagentstoadd)
  .then((results) => {
    AgenttoaddIDStore = [];
    results.forEach((agent) => {
      AgenttoaddIDStore.push({ AgentID: agent.AgentID });
      ctx.session.tempAgentID = agent.AgentID;
    });
    return AgenttoaddIDStore;
  })
  .then((res) => {
    console.log("agent ID: " + ctx.session.tempAgentID);
    console.log("done with two");
    return res;
  })
  .then((results) => insertcctblricaagents)
  .then((res) => {
    console.log("done with three");
    return res;
  })
  .then((results) => selectcctblricaagents)
  .then((res) => {
    console.log("done with four");
    return res;
  })
  .then((res) => selectcctblricaagentsnum)
  .then((result) => {
    AgentNewIDStore = [];
    result.forEach((agent) => {
      AgentNewIDStore.push({
        AgentID: agent.AgentID,
        MainNumber: agent.MainNumber,
      });
      ctx.session.AgentID = agent.AgentID;
      ctx.session.agentnumber = agent.MainNumber;
    });
    return AgentNewIDStore;
  })
  .then((res) => {
    console.log("cctblricaagentsnum agent ID: " + ctx.session.AgentID);
    console.log("done with five");
    return res;
  })
  .then((result) => insertcctblintblbotagents()) // 调用函数执行Update
  .then((res) => {
    console.log("done with six");
    return res;
  })
  .catch(err => { // 捕获整个链的异常,快速定位问题
    console.error('异步流程错误:', err);
  });

3. 额外验证建议

  • 执行Update后查看result对象的affectedRows属性,确认是否有行被修改。
  • 手动执行修正后的SQL语句,传入ctx.session中的实际值,验证是否能正确更新数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:40:16