脚本完成后,Node JS sequelize 不会自动关闭 [英] Node JS sequelize Do Not Close Automatically when the Script Done
问题描述
我在使用 sequelize.js 进行数据库连接设计时遇到了一些问题.我想要实现的是为我的应用程序数据库连接集中连接和配置文件.因此,我创建了一个文件名 database.js,如下所示.
I am facing some problem with my DB connection design with sequelize.js. What I want to achieve is to have a centralize connection and configuration files for my application DB connection. Therefore I have created a file name database.js as below.
const Sequelize = require("sequelize");
const dbConfig = require("../../config/database.json");
const db = {};
sequelize = new Sequelize({
dialect: dbConfig.dialect,
database: dbConfig.database,
username: dbConfig.username,
password: dbConfig.password,
host: dbConfig.host,
port: dbConfig.port,
operatorsAliases: false,
logging: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
db.Sequelize = Sequelize;
db.sequelize = sequelize;
module.exports = db;
如果有任何脚本要使用数据库,我只需要 database.js 文件.但是,当我的脚本完成时出现问题,由于sequelize连接没有关闭,进程没有退出(终端挂在那里).
If there is any scripts going to use database, I just have to require the database.js file. However, there is a problem when my script is finished, the process is not exiting (terminal hang there) because of the sequelize connection is not close.
我试图在 finally 块上调用 close 函数,但这会导致其他查询脚本无法正常工作(如果我在每个查询块上调用它),因为它们共享相同的瞬间.一旦第一个查询完成,连接将被关闭.
I have tried to call the close function on the finally block but this causing others query script not working (if I call it on every query block) due to the fact that they are sharing same instant. Once the first query done, then the connection will be closed.
sequelize
.query("SELECT * FROM users WHERE id = ?", {
replacements: [userId],
type: sequelize.QueryTypes.SELECT,
model: User,
mapToModel: true
})
.then(users => {
console.log(users);
})
.finally(() => {
sequelize.close();
});
我可以在最后一个查询中关闭连接,但是很愚蠢的是,每当我有一个最终需要执行的新查询时,我都必须将关闭移动到新的查询块.
I can close the connection on the last query, but it is stupid that whenever I got a new query that will need to execute at last, I will have to move the close to the new query block.
我正在寻找一个干净的代码,它可以帮助维护数据库连接,并且能够在执行所有脚本时自动关闭连接.
I am looking for a clean code that can help to maintain DB connection and also able to automatic close the connection when all scripts are executed.
推荐答案
sequelize.close()
返回一个promise,所以使用异步函数并调用等待 sequelize.close()
sequelize.close()
returns a promise so use async function and call
await sequelize.close()
这篇关于脚本完成后,Node JS sequelize 不会自动关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!