Promise执行后未触发then,数据库测试后无法关闭连接问题
解决数据库连接测试后未执行关闭操作的问题
问题分析
你遇到的核心问题是异步操作没有被正确等待:
- 最初的
test()方法内部调用了异步的this.db.authenticate(),但没有返回这个Promise,导致外部代码无法感知连接测试的完成状态。 - 你手动创建的
myPromise没有在db.test()的异步操作结束时调用resolve或reject,这个Promise会一直处于pending状态,后续.then()里的关闭连接代码永远不会执行。
解决方案
修改MySQLConnector类的test()方法,让它返回db.authenticate()生成的Promise,这样外部就能通过链式调用.then(),确保连接测试完成后再执行关闭操作。
修改后的db.js
import Sequelize from "sequelize"; import config from "./config"; class MySQLConnector { constructor(){ this.db = new Sequelize( config.ddbb_connection.database, config.ddbb_connection.user, config.ddbb_connection.password, { host: config.ddbb_connection.host, dialect: "mysql", operatorsAliases: false, pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } } ) }; test(){ // 返回authenticate的Promise,让外部可以链式调用等待异步操作完成 return this.db.authenticate() .then(() => { console.log("Connection to database: " + config.ddbb_connection.database + " has been established succesfully"); }) .catch(err => { console.log("Unable to connect to database: " + err); }); }; closeConnection(){ this.db.close(); console.log("Connection to database: " + config.ddbb_connection.database + " has been closed!!!"); } }; module.exports.MySQLConnector = MySQLConnector;
修改后的index.js
import express from "express"; import config from "./config"; import {MySQLConnector} from "./db"; const app = express(); let db = new MySQLConnector(); // 直接通过test()返回的Promise链式调用,确保测试完成后再关闭连接 db.test().then(() => db.closeConnection()); app.listen(config.server.port, () => { console.log("Server " + config.server.name + " listening on port " + config.server.port); });
为什么这样能解决问题
test()方法现在返回了Sequelize自带的Promise,意味着.then()会严格等待异步的连接测试操作完成后,才会执行关闭连接的逻辑。- 去掉了不必要的手动Promise包装,直接利用框架提供的异步管理能力,代码更简洁可靠,也避免了手动Promise未正确resolve的问题。
内容的提问来源于stack exchange,提问作者José Carlos
相关产品推荐
相关产品推荐

