Node.js搭配mongodb的脚本执行完成后无法正常退出是什么原因
问题原因分析
- 你封装的
end方法中,this.client.close()本身是返回Promise的异步方法,你没有等待它执行完成就直接返回了自定义的Promise,导致你调用await mongo.end()时,MongoDB连接实际还未完成关闭流程,Node.js事件循环中仍然持有连接的活跃句柄,因此进程不会自动退出。 - 其次构造函数中直接调用
this.client.connect()但未处理异步状态,本身也存在连接未就绪就调用数据库操作的潜在风险。
修复方案
1. 修正MongodbClient类的实现
const MongoClient = require('mongodb').MongoClient class MongodbClient { constructor(cfg) { this.cfg = cfg this.client = null this.db = null } // 新增初始化连接方法,不要在构造函数里执行异步逻辑 async init() { this.client = new MongoClient(this.cfg.mongoUrl, { useUnifiedTopology: true }); await this.client.connect(); // 等待连接完成 this.db = this.client.db(this.cfg.mongoDbName); } // 修正关闭连接方法 async end() { if (this.client) { await this.client.close() // 等待连接真正关闭完成 } return true } // .. 其他方法 } module.exports = { MongodbClient: MongodbClient }
2. 修正主脚本调用逻辑
// 初始化的时候要先await init完成再执行后续操作 const mongo = new MongodbClient(yourConfig) await mongo.init() parser.dosomething().then(async() => { await mongo.end() })
如果修复后依然存在进程不退出的情况,可以在调用await mongo.end()之后添加process.exit(0)主动退出进程,优先推荐修复异步等待逻辑让进程自然退出。
内容的提问来源于stack exchange,提问作者Ima Dev
相关产品推荐
相关产品推荐

