如何在Promise的then/catch中更新变量?Sequelize连接状态检查求助
Hey there! The issue with your current code is that sequelize.authenticate() runs asynchronously, but you're returning the data object before the Promise resolves or rejects. That means the data.status value you get back is still its initial state, not the updated one based on the connection check result.
Let's fix this with two clean, reliable approaches:
Approach 1: Use Async/Await (Recommended)
Since you already declared your function as async, this is the most straightforward way to handle the asynchronous operation:
const DBStatus = async (data) => { try { // Wait for the authentication process to finish await sequelize.authenticate(); data.status = true; console.log('Connection has been established successfully.'); } catch (err) { data.status = false; console.error('Unable to connect to the database:', err); } // Now data.status is correctly updated before returning return data; };
Approach 2: Return the Promise Chain
If you prefer sticking with .then()/.catch() syntax, make sure your function returns the entire Promise chain so the caller can wait for the final updated data object:
const DBStatus = (data) => { return sequelize .authenticate() .then(() => { data.status = true; console.log('Connection has been established successfully.'); return data; }) .catch(err => { data.status = false; console.error('Unable to connect to the database:', err); return data; }); };
Important Note on Calling the Function
No matter which approach you choose, this is an asynchronous operation—you need to handle the returned Promise when using DBStatus:
// Example usage with async/await const checkDatabaseStatus = async () => { const statusResult = await DBStatus({}); console.log('Current DB Connection Status:', statusResult.status); }; checkDatabaseStatus(); // Or with .then() syntax DBStatus({}) .then(statusResult => { console.log('Current DB Connection Status:', statusResult.status); });
内容的提问来源于stack exchange,提问作者Vini

