然后如何在Promise中更新变量并捕获

时间:2019-01-19 03:16:09

标签: javascript

我正在使用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

1 个答案:

答案 0 :(得分:0)

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