In my expressJS application, I am trying run 2 async promise returning functions in a sequence using thennable ...
connect2Redis(config.cache)
.then(connect2db())
.then(function() {
console.log("Accounting Server started successfully!");
})
})
.catch(function(e){
console.error("Failed to start Accounting server. Error: ", e);
})
The two fns 'connect2Redis' and 'connect2db' are implemented as below:
function connect2Redis(opts) {
var connectingMsg = "Connecting to Redis Cache @" + config.cache.host + ":" +config.cache.port;
process.stdout.write(connectingMsg);
return new Promise(function(resolve, reject){
var redisClient = redis.createClient(opts);
redisClient.on('ready', function(){
console.log(" [ " + "OK".green + " ]");
return resolve(redisClient);
})
redisClient.on('error', function(e){
console.log("[" + "FAIL".red + "]");
return reject(e);
})
});
}
function connect2db() {
process.stdout.write("Synchronizing to database...");
return DB.sequelize.sync().then(function() {
console.log(" [ " + "OK".green + " ]");
}).catch(function(e) {
console.log("[" + "FAIL".red + "]");
return e;
});
}
I am expecting the two fns to execute "one-after-another", since I had chained them using the thennable. There are two log statements one before connection and one after connection. If everything goes well, I am supposed to see logs like this...
Connecting to Redis Cache @localhost:6379 [ OK ]
Synchronizing to database... [ OK ]
Accounting Server started successfully!
But the display gets mixed up, and I see something like this.
Connecting to Redis Cache @localhost:6379Synchronizing to database... [ OK ]
Accounting Server started successfully!
[ OK ]
I was expecting that log statements in conenct2Redis fn should get printed without getting interrupted by logs from connect2db, because this 2nd fn is invoked after completion of connect2Redis, using then(...)
Is there something I am missing here?
You need to pass a reference to the function instead of calling the function
connect2Redis(config.cache)
.then(connect2db)