I'm having a strange issue using NodeJS v0.10.33 / Javascript. I'm also using Hapi 8.0.0
, mongoose
, moment
and request
libs.
I'm trying to run a simple IF that must waits for a method call to know if the conditional is TRUE or FALSE. Instead the default run, my code is running the conditional contents BEFORE the conditional itself. It's like always running "TRUE" without waiting the return from the called method.
I have something like that:
function isUpdated(){
var updated = true;
if (updated) {
console.log("Updated (inside isUpdated)");
} else {
console.log("Not updated (inside isUpdated)");
}
}
if (!isUpdated()) {
console.log("Not updated. Updating..");
} else {
console.log("Updated");
}
But when I run my server, I got:
[paladini@pet01 myFolder]$ node server.js
Server running at: http://pet01.inf.ufsc.br:3000
Not updated. Updating..
Updated (inside isUpdated)
As you can see, the IF content is running before the conditional itself.
My full code is following (update()
is executed first):
function isUpdated(myTicker) {
myTicker = myTicker || undefined
Ticker.count({}, function(err, count){
if (!err) {
// Verify if must check all tickers or just one.
if (myTicker == undefined) {
if (count == 0) {
console.log("Exchanges count = 0");
} else {
// Checking if the database is outdated (must update every 2 minutes).
Ticker.find().lean().exec(function(err, allTickers){
if (!err) {
if (moment(allTickers[0].updatedAt) >= moment().subtract(2, 'm')) {
console.log("Entered IF, already updated.");
return true;
}
} else {
console.log("Erro!");
}
});
}
} else {
console.log("Ticker defined, nothing to do.");
}
}
return false;
});
}
function update(callback) {
var atualizado = isUpdated();
if (!atualizado) {
// Updating exchanges informations.
var exchangesUpdated = {value: 0};
var updateAll = function() {
api.bitcoinToYou.updateTicker(exchangesUpdated);
}
console.log("Not updated. Updating..");
updateAll();
// Waiting to run the callback.
var timeoutTime = 50;
var myFunctionToTimeout = function() {
// Get the exchanges count
Ticker.count({}, function(err, count){
if (!err) {
if (exchangesUpdated["value"] != count) {
setTimeout(myFunctionToTimeout, timeoutTime);
} else {
callback();
}
}
});
}
setTimeout(myFunctionToTimeout, timeoutTime);
} else {
console.log("Updated.")
callback();
}
}
We have the following scenarios:
- First time the update() is executed: the database is updated and return.
- Executed before 2 min: not updated and return.
- Executed after 2 min: the database is updated and return.
The problem is with the 2º scenario: the database is always updated (I think isUpdated() method is okay, the update() is the wrong one). When I simulate the 2º scenario, I have this log in the terminal:
[paladini@pet01 myProject]$ node server.js
Server running at: http://pet01.inf.ufsc.br:3000
Not updated. Updating..
Entered IF, already updated.
What I'm doind wrong? This is an issue with NodeJS or Hapi?