I am new to Nodejs.I want to convert this code to promises (nodejs).This includes four callback function get(),abc1(),pqr(),xyz(). It gives error of "cannot read property 'then' of undefined" Can anyone fix it? I am trying it to convert into promises from this example here
var jwt = require('jwt-simple');
var mysql = require('mysql');
var async = require('async');
var Promise = require('bluebird');
var connection = mysql.createConnection({
host: 'localhost',
port: 3306,
database: 'abc',
user: 'root',
password: ''
});
var auth = {
login: function (req, res) {
var username = req.body.username || '';
var password = req.body.password || '';
console.log(req.body);
//This is get() function
function get(err, rows) {
connection.connect(function (err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
} else {
console.log("connected to database");
connection.query("SELECT count(id) as count from abc where name=? AND email=?", [username, password], function (err, rows) {
if (err) {
throw err
} else {
b = rows;
console.log(b);
}
});
}
});
}
//this is abc1() function
function abc1(err, rows) {
console.log("onresult");
if (err) {
throw err;
console.log("error in Query");
} else {
if (rows[0].count != 1) {
//xyz(result,xyz);
res.json({
"status": 401,
"message": "Invalid credentials"
});
} else {
connection.query("SELECT email from abc where name=? AND email=?", [username, password], function (err, rows) {});
//res.json(genToken("ayush"));
}
}
}
//This is xyz() function
function xyz(err, rows) {
if (err) {
console.log(err);
}
console.log(rows);
connection.query("SELECT name from abc where name=? AND email=?", [username, password], function (err, rows) {});
}
//This is pqr() Function
function pqr(err, rows) {
if (err) {
console.log(err);
}
console.log(rows);
}
get()
.then(function (rows) {
// do something...
//console.log("hellow1");
return abc1();
})
.then(function (rows) {
// do something...
console.log("hellow2");
return xyz();
})
.then(function (rows) {
// the third and final async response
console.log("hellow3");
return pqr();
})
.then(function (rows) {
// the third and final async response
console.log("hellow4");
})
.fail(function (err) {
// handle any error resulting from any of the above calls
throw err;
})
.done();
}
}