使用pg-promise的bulkInsert函数调用后无成功/错误反馈求助
问题
我编写了一个使用pg-promise执行批量插入操作的bulkInsert()函数,当使用await关键字调用该函数时,它执行后没有任何成功或错误的反馈信息,不确定是否遗漏了某些内容,希望能得到帮助。
使用版本:pg-promise v11.5.4,Node.js v18.17.1
代码如下:
const pgp = require('pg-promise'); const db = pgp({ host: 'localhost', port: 5443, database: 'data_base', user: 'user_name', password: 'pass_word', }); ....... ....... ....... const bulkInsert = async (data) => { //function when called, executes without any result(success/failure) const cs = new pgp.helpers.ColumnSet(['col_A', 'col_B','col_C'], { table: 'table_name' }); db.tx('massive-insert', t => { const processData = data => { if (data) { const insert = pgp.helpers.insert(data, cs); return t.none(insert); } }; return t.sequence(index => getNextData(t, index, data).then(processData)); }) .then(() => { console.log('Success'); }) .catch(error => { console.log(error); }); function getNextData(t, pageIndex, data) { return new Promise((resolve, reject) => { const batchSize = 1000; const nextDataBatch = []; try{ for (let i = pageIndex; i < data.length; i += batchSize) { const batch = data.slice(i, i + batchSize); nextDataBatch.push(batch); } if (nextDataBatch.length === 0) { resolve(null); } else { resolve(nextDataBatch); } } catch(err){ reject(err); } }); } };
问题分析与修复
你的代码存在两个核心问题,导致调用后无反馈:
- 未返回Promise给调用者:
bulkInsert是async函数,但内部调用db.tx()后没有返回这个Promise,导致await无法等待操作完成,函数直接空返回。内部的then/catch仅在函数内部执行,调用者无法感知结果。 getNextData逻辑错误:该函数会一次性生成所有数据批次,不符合t.sequence的预期——t.sequence需要每次回调返回单个批次,直到没有数据为止,而非一次性返回所有批次。
修复后的代码:
const pgp = require('pg-promise'); const db = pgp({ host: 'localhost', port: 5443, database: 'data_base', user: 'user_name', password: 'pass_word', }); const bulkInsert = async (data) => { const cs = new pgp.helpers.ColumnSet(['col_A', 'col_B','col_C'], { table: 'table_name' }); const batchSize = 1000; const totalBatches = Math.ceil(data.length / batchSize); // 返回db.tx的Promise,让await能等待整个事务完成 return db.tx('massive-insert', t => { const processBatch = batch => { const insertQuery = pgp.helpers.insert(batch, cs); return t.none(insertQuery); }; // t.sequence按批次顺序执行插入 return t.sequence(index => { if (index >= totalBatches) { // 没有更多批次,返回null终止序列 return null; } const start = index * batchSize; const end = start + batchSize; const currentBatch = data.slice(start, end); return processBatch(currentBatch); }); }) .then(() => { console.log('批量插入成功'); return true; // 返回成功标识给调用者 }) .catch(error => { console.error('批量插入失败:', error); throw error; // 抛出错误,让调用者的try/catch能捕获 }); };
额外说明:
- 移除了冗余的
getNextData函数,直接在t.sequence回调中计算当前批次,逻辑更贴合pg-promise的设计。 - 修复后,调用
await bulkInsert(data)时会等待整个插入流程完成,成功时返回true,失败时抛出错误,调用者可通过try/catch处理结果。 - 若希望由调用者自行处理成功/失败逻辑,可将函数内的
then/catch移除,仅返回db.tx()的Promise。
内容的提问来源于stack exchange,提问作者artificial unintelligence
相关产品推荐
相关产品推荐

