Return 来自 sequelize 查询的值

Return a value from sequelize query

我是续集的新手。我正在使用 mysql 作为我的数据库。我有一个 sequelize 查询,它从数据库中找到电子邮件 ID。通过使用此查询的结果,我获得了该行的 ID。现在我需要 return 这个值。有人可以帮我怎么做吗?

这是我的代码。

var userId = getUserId(email_address);
function getUserId(email_address) {
   models.users.findOne({
     where: {
       email: email_address
     }
   }).then(function(result) {
      if (result) {
        var applicantId = result.id;
        return applicantId;  // This is what I need to do
      } else {
        console.log("Could not find Email");
      }
   });
}

这里我需要return调用函数的变量applicantId。

对数据库的 Sequelize 调用是异步的,因此您需要稍微更改代码以使用 promise。像这样:

function getUserId(email_address) {
   return models.users.findOne({
     where: {
       email: email_address
     }
   });
}

getUserId("some@email.com").then(function(result){
   console.log(result.id);
});

查看模拟您的场景的 this fiddle