I have a scenario where I need to get the records from MySQL database and update in redis cache and close the MySQL and redis connection.
Steps:
- Open MySQL connection
- Get records from MySQL database on success
- Update Redis cache on success from MySQL Query Result
- Close the MySQL db connection.
I am trying to do using Bluebird promises but not getting appropriate results.
Problem in below code is done is getting called initially and even in processBreakingNewsData function which supposed to be executed last.
Please correct me in the places where I have done mistake
Below is my node.js code
constants.js file
var Promise = require('bluebird');
module.exports = {
getRedisConnection: function () {
return require("redis").createClient(6379, 'XXXX', { auth_pass: 'XXXX' });
},
getMySqlConnection: function () {
var conObj = { host: "localhost", user: "root", password: "", database: "deccan" };
var connection = require("mysql").createConnection(conObj);
return new Promise(function (resolve, reject) {
connection.connect(function (error) {
if (error)
reject(error);
else
resolve(connection);
});
});
}
};
testing.js file
var constants = require("./constants.js");
var Promise = require('bluebird');
constants.getMySqlConnection().then(processBreakingNewsData)
.catch(function (e) {
console.log("Error : " + e);
}).done(function () {
console.log("Finished");
});
function processBreakingNewsData(connection) {
return new Promise(function (resolve, reject) {
connection.query("select id, text, DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') as 'created_at' from breakingnews;", function (error, results) {
connection.end();
if (error)
reject(error);
else
resolve(results);
});
}).then(function (results) {
return new Promise(function (resolve, reject) {
var value = "";
if (results.length > 0)
value = JSON.stringify(results);
var client = constants.getRedisConnection();
client.set("bnews", value, function (err, reply) {
if (err)
reject(new Error("Error during Update of BreakingNews : " + err));
else
resolve(reply);
});
});
}).catch(function (e) {
console.log("Error during Update of BreakingNews : " + e);
}).done(function (result) {
console.log("Breaking News Updated in Redis.");
});
}