SQL 密码每 24 小时过期一次(间隔可能随时更改,恕不另行通知),因此我想在运行 SQL 查询之前使用 Sequelize beforeConnect Hook 验证身份验证。
如果没有 async await,SQL 查询将失败,然后进行身份验证,前面的查询将通过。我想以异步方式运行代码,因此没有 SQL 查询失败。请帮我解决这个问题。
const sequelize = new Sequelize(database, username, password, params);
sequelize.beforeConnect(async (currConfig) => {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
});
最佳答案
您可以 promise beforeConnect
let currConfig = await prepare(sequelize);
try {
await sequelize.authenticate();
console.log("Connection has been established successfully.");
} catch (error) {
console.error("Unable to connect to the database:", error);
}
function prepare(sequelize) {
return new Promise(res => {
sequelize.beforeConnect(config => res(config));
});
}
只要确保你的函数有 async
在它面前
关于javascript - 无法通过 sequelize.authenticate() 方法使用异步等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65002748/