I'm trying to make a simple query on my database with 2 parameters, and I'm having trouble trying to reformat this code using Promises/Async to avoid callback hell. Here is the code:
module.exports = {
getDailyRaw: function(school, meal, callback) {
var sql = "SELECT * FROM daily WHERE school = ? AND meal = ?";
pool.getConnection(function(err, conn) {
if(err) { console.log(err); callback(true); return; }
conn.query(sql, [school, meal], function(err, results) {
conn.release();
if(err) { console.log(err); callback(true); return; }
callback(false, school, results);
})
})
}, ....
I've been constantly trying to look up tutorials on fixing this issue, but haven't been able to implement/understand them properly.
EDIT: I am now using the 'promise-mysql' library to get the job done, but I am still having trouble with chaining together multiple queries. How would I pass over the already established connection into another then statement so that I can call for a query again? Updated code:
getDaily: function(school, meal, callback) {
pool.getConnection().then(function(conn) {
var sql = "SELECT * FROM daily WHERE school = ? AND meal = ?";
return conn.query(sql, [school,meal]);
}).then(function(rows) {
var qMarks = "";
var foodNames = [school];
rows.forEach(function(item) {
foodNames.push(item.name);
qMarks += "?,";
});
qMarks = qMarks.substring(0, qMarks.length - 1);
var sql = "SELECT * FROM foods WHERE school = ? AND name IN (" + qMarks + ")";
return conn.query(sql, foodNames);
}).then(function(finalData) {
callback(finalData);
}).catch(function(err) {
callback(null);
console.log(err);
})
},