我尝试将密码从数据库返回到另一个javascript文件。该函数将正确检索数据。但是当我将值返回给另一个函数时,它将被更改为undefined。我想将密码从model.js
返回到controller.js
。
代码: model.js
const Sequelize = require('sequelize'); //import sequelize orm
// connect with psql db
var connection = new Sequelize('emd','postgres','test',{
dialect : 'postgres'
});
//create a table;
var student = connection.define('student',{
name : {
type : Sequelize.STRING,
allowNull : false},
email : {
type: Sequelize.STRING,
unique : true,
allowNull : false},
password : {
type : Sequelize.STRING,
allowNull : false },
mobile : {
type: Sequelize.BIGINT(11),
unique : true,
allowNull : false }
});
var methods = {};
methods.signup = function(u_name,u_email,u_password,u_mobile){
connection.sync().then(function(){
student.create({
name : u_name,
email : u_email,
password : u_email,
mobile : u_mobile
});
});
}
methods.login = function(email_id){
connection.sync().then(function(){
student.findOne({where : {email : email_id }} ).then(results =>{
return results.dataValues.password;
});
});
}
exports.fun = methods;
代码:Controller.js
var model = require('./model.js')
var methods={}
methods.login = function(email,password){
let res = model.fun.login(email)
console.log(res);
if(password===res){
console.log("success");
}
else {
console.log("failure");
}
}
exports.cont = methods
答案 0 :(得分:0)
因为函数Vehicle
是异步的,所以在从这个函数得到响应之前,它会移动到下一个语句,返回model.fun.login
。
undefined
答案 1 :(得分:0)
您可以退回Promise并在then
内的controller
区块内处理。
reutrn student.findOne({where : {email : email_id }} ));
这将返回承诺。在控制器中,您可以将方法调用为
model.fun.login(email).then(function(result){
console.log(JSON.stringfy(result));
});
答案 2 :(得分:0)
添加到@Sagar Jojoriya,
像这样更改你的model.js
methods.login = function(email_id, callbackFun){
connection.sync().then(function(){
student.findOne({where : {email : email_id }} ).then(results =>{
console.log("debug pass => ", results.dataValues.password);
callbackFun(results.dataValues.password);
});
});
}
在你的controller.js
中methods.login = function(email,password){
model.fun.login(email, function(resPassword) {
if(password === resPassword){
console.log("success");
} else {
console.log("failure");
}
})
}