You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Promise的then/catch中更新变量?Sequelize连接状态检查求助

Fixing Your Sequelize Connection Status Function

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:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:43:34