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

JavaScript异步回调中调用InsertToDataBase插入数据不生效问题求解

问题原因

  • axios的then链式调用传递异常:第一个.then回调仅执行了DOM赋值操作,没有返回response对象,导致第二个.then接收的response参数为undefined,执行response.data时直接抛出异常,后续的插入代码从未被触发执行。
  • PostgreSQL客户端单例复用错误:在InsertToDataBase.js模块顶层仅初始化了一个全局Client实例,每次调用插入函数后都会执行client.end()销毁客户端实例。第一次外部调用InsertToDataBase.insertdatatolamp0(1,1)执行完成后,客户端已经被关闭,后续在函数内再次调用插入方法时,已销毁的客户端无法正常连接数据库执行操作。

解决方案

1. 修复axios链式调用逻辑

在第一个.then回调末尾添加return response,保证后续链式调用能拿到正确的响应对象:

.then(function(response) {
      document.getElementById("rn0").textContent = response.data['m2m:cin'].rn;
      document.getElementById("ty0").textContent = response.data['m2m:cin'].ty;
      return response; // 新增该行传递响应对象
})

如果无特殊逻辑要求,也可以直接合并两个.then的代码,减少不必要的链式传递。

2. 修复PostgreSQL客户端初始化逻辑

不要复用全局单例Client,每次调用插入函数时新建独立的Client实例,执行完成后销毁:
修改InsertToDataBase.js代码如下:

const {Client} = require('pg')
// 抽离公共数据库配置
const dbConfig = {
    user:"postgres",
    password:"admin",
    host:"localhost",
    port:"5432",
    database:"postgres",
}
// 改用async/await写法简化异步逻辑
async function insertdatatolamp0(rn0,ty0){
  const client = new Client(dbConfig)
  try {
    await client.connect()
    console.log("connected successfuly")
    await client.query("insert into lamp0 values ($1,$2)",[rn0,ty0])
  } catch(e) {
    console.log(e)
  } finally {
    await client.end()
  }
}
module.exports = { insertdatatolamp0 };

可选优化:使用连接池提升性能

如果插入操作频率较高,每次新建客户端开销过大,可以改用pg连接池复用连接:

const { Pool } = require('pg')
// 全局初始化连接池
const pool = new Pool({
    user:"postgres",
    password:"admin",
    host:"localhost",
    port:"5432",
    database:"postgres",
})
async function insertdatatolamp0(rn0,ty0){
  const client = await pool.connect()
  try {
    await client.query("insert into lamp0 values ($1,$2)",[rn0,ty0])
  } catch(e) {
    console.log(e)
  } finally {
    client.release() // 归还连接到连接池,而非销毁
  }
}
module.exports = { insertdatatolamp0 };

内容的提问来源于stack exchange,提问作者Badr-Eddine El mostaine

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:06:01