我是 Sequelize 的新手。我正在使用 mysql 作为我的数据库。我有一个 sequelize 查询,它从数据库中找到电子邮件 ID。通过使用此查询的结果,我获得了该行的 ID。现在我需要返回这个值。有人可以帮我怎么做吗。
这是我的代码。
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");
}
});
}
这里我需要将变量 applicantId 返回给调用函数。
最佳答案
Sequelize 对数据库的调用是异步的,因此您需要稍微更改代码以使用 promises。像这样:
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模拟你的场景
关于mysql - 从 sequelize 查询返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36954637/