Keydose
Keydose

Reputation: 729

Node.js - Typical callback issue

I added some comments into the code so that you can see what the issue is, basically... I want currency to be 'usable' after the db.where() function so that it can be used in the if statement. This'll no doubt be simple enough to fix, but I'm terrible. Thank you for your time.

db.where('users', {name: user.username}).then(function(result) {
    var currency = result.items[0].currency;
    console.log(currency);
});
console.log("Program gets to this point without error.");
console.log(currency); // Doesn't work as currency is no longer defined.
if (typeof args[2] == 'number' && args[2] <= currency) {
    var betOkay = true;
    console.log("betOkay is " + betOkay);
}

Upvotes: 0

Views: 53

Answers (3)

Juan Ortiz
Juan Ortiz

Reputation: 11

JavaScript has function scope. Variables are available within the function they are defined. But JavaScript also has closures which allow inner functions access to variables defined in the outer functions (see JavaScript closures).

The variable currency is defined in the anonymous function you're using for your callback. So its scope is the callback function. This is why is not accessible elsewhere.

As the other answers indicate you can achieve your goal by including the code that needs to access currency within the callback but you can also declare the variable currency in the outer scope and set it (via closure) on the callback.

See below:

var currency; // defined in the scope where it will be used

db.where('users', {name: user.username}).then(function(result) {
    currency = result.items[0].currency; // has access to it via closure
    console.log(currency);
});
console.log("Program gets to this point without error.");
console.log(currency); 
if (typeof args[2] == 'number' && args[2] <= currency) {
    var betOkay = true;
    console.log("betOkay is " + betOkay);
}

Upvotes: 1

Gaurav Dhiman
Gaurav Dhiman

Reputation: 610

You should use currency in callback.

db.where('users', {name: user.username}).then(function(result) {
    var currency = result.items[0].currency;
    console.log(currency);
    if (typeof args[2] == 'number' && args[2] <= currency) {
        var betOkay = true;
        console.log("betOkay is " + betOkay);
    }
});

Upvotes: 1

mscdex
mscdex

Reputation: 106736

You have to move your code into the callback or another function that you call from your callback. The callback is executed asynchronously, so it's not that currency is no longer defined, but it's that it's not defined yet and it's not in the same scope.

Upvotes: 5

Related Questions