2

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:

  1. First time the update() is executed: the database is updated and return.
  2. Executed before 2 min: not updated and return.
  3. 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?

Paladini
  • 4,522
  • 15
  • 53
  • 96
  • is your isUpdated() function supposed to return true of false? your if statement is checking to see if your isUpdated() function is. – Entrabiter Dec 31 '14 at 00:33
  • 3
    Your simple code !-== the actual code. Your real code is ASYNCHRONOUS. You can not return from an asynchronous method. Basically you ordered a delivery pizza and you are eating it before it got to your house. It is not possible. – epascarello Dec 31 '14 at 00:35
  • But there's a way I can eat the pizza after the pizza come to my home? It should be possible, what can I do to solve my problem? – Paladini Dec 31 '14 at 00:46
  • All you guys are upvoting the @epascarello comment but anyone gives me a solution. Guys, please, what can I do to solve my problem? Please! – Paladini Dec 31 '14 at 01:36
  • http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call You do the logic in the callback or you look into promises. – epascarello Dec 31 '14 at 01:52

1 Answers1

-1

You're forgetting to return a value from isUpdated

Pasha Bitz
  • 787
  • 6
  • 9
  • 2
    whilst strictly correct, the OP appears to be calling an async function, which means that he cannot useful `return` any value (unless that value is a `Promise`). – Alnitak Dec 31 '14 at 00:49