I am implementing an API to manage a MySQL database from Nodejs, and I want to keep my code clean as the work I intend to do can take me to have a lot of nested connection.query functions all over the place, so I've decided to separate as many as the queries I could into separate functions.
To start I wanted to do a function to check if there is an existing element already on the table, like this:
function validator(item) {
return new Promise(function(err,done) {
connection.query('select * from items where item_id = ?', [item.id] , function(err,rows){
console.log(rows);
console.log("above row object");
if (err) {
return done(false);
}
if (rows.length) {
console.log('That item is already in the DB.');
return done(false);
} else {
console.log('That item is new.');
return done(true);
}
});
});
}
And then I want to use it like this:
var insert = function (item, done) {
validator(item).then(function(err,done) {
console.log('here I go: '+done);
if(done) {
console.log('good');
} else{
console.log('bad')
}
);
}
But it does not work like I expected, the first function accurately detects if an item exists or not, but the second one never never reaches the "here I go" print.
I have checked Use promise to process MySQL return value in node.js, Javascript Promise node.js? and Javascript & promises with Q - closure problems in promises but the conclussion I reach is that this is a classic PEBCAK problem, such as that I'm a very incompetent javascript programmer and can't wrap my head around the callbacks and promises all that well so I'm managing them the wrong way.