I am trying to build a login API using NodeJS, but my code is not doing what I expect it to. I am very new to js, promises and all so please simplify any answer if possible.
From what I can see in the output of my code, the first promise part does not wait until the function findUsers(...) is finished.
I have a routes file where I want to run a few functions sequentially:
- Find if user exist in database
- if(1 is true) Hash and salt the inputted password
- ... etc
The routes file now contains:
var loginM = require('../models/login'); var loginC = require('../controllers/login'); var Promise = require('promise'); module.exports = function(app) { app.post('/login/', function(req, res, next) { var promise = new Promise(function (resolve, reject) { var rows = loginM.findUser(req.body, res); if (rows.length > 0) { console.log("Success"); resolve(rows); } else { console.log("Failed"); reject(reason); } }); promise.then(function(data) { return new Promise(function (resolve, reject) { loginC.doSomething(data); if (success) { console.log("Success 2"); resolve(data); } else { console.log("Failed 2"); reject(reason); } }); }, function (reason) { console.log("error handler second"); }); }); } And the findUser function contains pooling and a query and is in a models file:
var connection = require('../dbConnection'); var loginC = require('../controllers/login'); function Login() { var me = this; var pool = connection.getPool(); me.findUser = function(params, res) { var username = params.username; pool.getConnection(function (err, connection) { console.log("Connection "); if (err) { console.log("ERROR 1 "); res.send({"code": 100, "status": "Error in connection database"}); return; } connection.query('select Id, Name, Password from Users ' + 'where Users.Name = ?', [username], function (err, rows) { connection.release(); if (!err) { return rows; } else { return false; } }); //connection.on('error', function (err) { // res.send({"code": 100, "status": "Error in connection database"}); // return; //}); }); } } module.exports = new Login(); The output i get is:
Server listening on port 3000 Something is happening error handler second Connection So what I want to know about this code is twofold:
- Why is the first promise not waiting for
findUserto return before proceeding with the if/else and what do I need to change for this to happen? - Why is
error handler secondoutputed but notFailed?
I feel like there is something I am totally misunderstanding about promises. I am grateful for any answer. Thanks.