node-pg连接提前终止:finally块在Promise.all完成前执行求助
问题分析与解决建议
核心问题:Promise.all 参数传递错误
你代码里的Promise.all调用方式有误,它只接受一个包含Promise的数组作为参数,但你传了两个独立的数组参数:
await Promise.all(employees.map(createEmployee), customers.map(createCustomer));
这会导致customers.map(createCustomer)这个Promise数组根本没被纳入等待队列,函数会直接进入后续逻辑,最终finally块提前执行client.end()断开连接,此时createCustomer的异步操作还没完成,就出现了连接被终止的问题。
修复方案
把两个Promise数组合并成一个数组传入Promise.all,同时记得client.connect()也是异步操作,需要加上await(否则可能出现连接还没建立就执行后续数据库操作的隐患):
const rebuildDB = async () => { try { await client.connect(); // 加上await确保连接建立完成 await dropTables(); await createTables(); // 将两个Promise数组合并为一个数组传入Promise.all await Promise.all([ ...employees.map(createEmployee), ...customers.map(createCustomer) ]); } catch (err) { console.error(err); // 用console.error更适合输出错误信息 } finally { await client.end(); // 加await确保连接正常关闭完成 } }; rebuildDB();
额外说明
Promise.all会等待数组中所有Promise都完成才会继续执行后续代码,合并数组后就能保证createEmployee和createCustomer的所有异步操作都完成后,才会进入finally块关闭连接。client.connect()和client.end()都是异步方法,加上await可以避免因异步时序问题导致的潜在错误。
内容的提问来源于stack exchange,提问作者James Kehs
相关产品推荐
相关产品推荐

