harshvardhan
harshvardhan

Reputation: 805

Returning variable value in sailsJS

I am trying to write a controller in sailsjs

module.exports = {

someFunction: function(req, res){

    var userID = req.param('id')

    User.findUserName(userID, function(err, receiverName){
        if(err){
            res.serverError(err);
        }else{
            ReceiverName = receiverName;
        }
    });
    console.log("#####################################");
    console.log(ReceiverName);
    console.log("#####################################");
    .
    .
    .
    .

But when I deploy the controller, restart the sails app and call this function through the URL, I am getting the following error on the console:

error: Sending 500 ("Server Error") response: 
 ReferenceError: ReceiverName is not defined

I tried to declare the variable ReceiverName to be global, but still cant sort it out. I need guidance on making it global so that I assign value to it inside the else part and use it anywhere inside the controller.

Note 1:

However, when I am printing the value of the variable on console right inside the else block using the code:

User.findUserName(userID, function(err, receiverName){
    if(err){
        res.serverError(err);
    }else{
        console.log("#####################################");
        console.log(receiverName);
        console.log("#####################################");
    }
});

the value is printed perfectly.

Note 2:

I am already making asynchronous call to retrieve the receiverName, so it is not a doubt about returning the response from asynchronous calls. I am looking for method to store the response in a variable that can be used further.

Upvotes: 2

Views: 710

Answers (1)

Meeker
Meeker

Reputation: 5979

Your Note 2 is a little bit confusing so I'm not sure if you understand that the reason it does not work in your first example is because the User.findUserName() has not finished running before you execute your console.log().

Remember, the database calls are async. So any values you want to use from that database call have to run after it finishes. The only way to ensure that is to make sure your code runs inside the callback.

That is why the second example works. The code that needed the receiverName variable ran inside the callback. Try this, it is pretty much the same thing as your second example ...

User.findUserName(userID, function(err, receiverName){
    if(err){
        res.serverError(err);
    }else{
       doStuffWith(receiverName)
    }
});
var dostuffWith = function(ReceiverName){
    // all the code that you want to use ReceiverName should be in here.
    console.log("#####################################");
    console.log(ReceiverName);
    console.log("#####################################");    
}

You should do some reading on programming patterns with Node.js, async and callbacks. Like this

http://book.mixu.net/node/ch7.html

Upvotes: 3

Related Questions