我正在使用sequalize并试图构建一个小的功能来检查数据库连接状态
const DBStatus = async(data)=>{
sequelize
.authenticate()
.then(() => {
data.status=true;
console.log('Connection has been established successfully.');
})
.catch(err => {
data.status=false;
console.error('Unable to connect to the database:', err);
});
return data
}
我要根据承诺状态返回data.status
答案 0 :(得分:0)
使用async
时,应将await
关键字与try / catch
一起使用,而不是.then
和catch
const DBStatus = async (data) => {
try {
const result = await sequelize.authenticate();
data.status = true;
console.log('Connection has been established successfully.');
// if you want to resolve this promise with a value then use return
return result
} catch(err) {
data.status=false;
// if you want to reject the promise with a value then use throw
throw err;
console.error('Unable to connect to the database:', err);
}
}