Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize return result from .then

I have the following code :

var ORM = require('../helpers/mysql_orm');
var log = require('../helpers/logger');  

function UserModel() {

   this.User = ORM.define('User', {

        }, {
        tableName: 'User',
        timestamps: false,
        }); 
}


UserModel.prototype.findOneByCredinitals = function (creditinals) {

    this.User.findOne({ 
            attributes:['username','id'],
            where: 
             { 
              username:creditinals.principal,
              password:creditinals.creditinal}
            })
            .then(function(user) {
           console.log("inside then function"+user);
            return user;
    })
   // console.log(result);

},
UserModel.prototype.findAllByLimit = function(req,res) {


}


module.exports= new UserModel;

//app.js

var result = User.findOneByCredinitals({principal: 'admin',creditinal:'danieladenew'});

console.log("returned "+result);

This the result from app.js

------------------------------------------------
returned undefined
inside then function User Sequelize Instance i.e Useriffound and displayed.

How do i return user object from then to app.js code please ?

like image 912
Daniel Adenew Avatar asked Oct 03 '16 07:10

Daniel Adenew


1 Answers

You need to return the promise in order for the data to appear.

UserModel.prototype.findOneByCredential = function (credentials) {

    return this.User.findOne({ 
        attributes: ['username', 'id'],
        where: { 
            username: credential.principal,
            password: credential.credential
        }
    }).then(function(user) {
            console.log("inside then function"+user);
            return user;
        }
    });
},

Also, it might be a good idea to add a catch block. If the query fails, you will have no idea otherwise

like image 87
Tikkes Avatar answered Sep 28 '22 00:09

Tikkes