简体   繁体   English

如何更新承诺内的变量然后捕获

[英]How to update variable inside promise then & catch

I am using sequalize & trying to build a small function to check DB connection status我正在使用 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
}

I want to return data.status based on promise status我想根据承诺状态返回 data.status

When you use async you should use the await keyword with try / catch , not .then and catch当您使用async您应该将await关键字与try / catch ,而不是.thencatch

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM