【问题标题】:How to return a boolean from findOne function MySQL如何从 findOne 函数 MySQL 返回布尔值
【发布时间】:2021-02-16 02:38:12
【问题描述】:

我想使用findOne 的结果作为if 语句的条件。我无法返回 truefalse,我看到 async 函数有所不同,但尽管多次尝试都没有成功。

Controller.js

  // Find a single User with a sub
exports.findOne = (req, res) => {
const sub = req.params.sub;

User.findOne({sub})
  .then(data => {
res.send(data);
  })
  .catch(err => {
res.status(500).send({
message: "Error retrieving User with sub=" +sub
});
  });
};

前端:

//INFO SAVE AND UPDATE CONDITION

async function exist() {
let x = await InfoDataService.get(data.sub)
console.log(x);
if (x === null) {

return true;

}
return false;
}

if ( exist() ) {
    InfoDataService.create(data)
      .then((response) => {
        console.log('create', response.data);
        setInfo({
          id: response.data.id,
          sub: response.data.sub,
          email: response.data.email,
          firstname: response.data.firstname,
          lastname: response.data.lastname
        });
      })
      
  } else {
    InfoDataService.update(sub, data)
      .then((response) => {
                
        console.log(response.data);
      })
      .catch((e) => {
        console.error(e);
      });
  }
  };

【问题讨论】:

    标签: mysql node.js asynchronous async-await sequelize.js


    【解决方案1】:

    您有两种选择。两者只是互补。

    // option 1 
    if (x) {
        return true;
    }
    return false;
    
    // OR
    // option 2
    if (!x) {
        return false;
    }
    return true;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 2017-06-07
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      相关资源
      最近更新 更多