0

My userProfileController.js result is undefined

var UserProfileSerice = require('../../Services/User/UserProfileService.js');

module.exports = function(app){

app.get('/tester' , ensureAuthenticated, function(req, res){


    var sonuc ;

    UserProfileSerice.getUserByEmail(function(result){
        sonuc = result;
    })

    console.log('sonuc' +sonuc);

    res.render('UserPages/userPage');
})

}

and

this function is inside UserProfileSerice.js file I can not get the result that callback is not working

var UserModel = require('../../Models/User/UserModel.js');
var thinktConfig = require('../../Utils/rethinkdb/config.js');
var thinky = require('thinky')(thinktConfig.rethinkdb);
module.exports ={



getUserByEmail : function (callback) {

    UserModel.filter({email: "slmkrnz@gmail.com"}).run().then(function(result) {
        callback(result);

    });

}}
slmkrnz
  • 23
  • 1
  • 4

1 Answers1

1

It simply because the call your are making is async. The callback is defined, but the execution tries to execute console.log(myResult) before the callback returns. I bet if you replace your code by this:

var myResult;
UserModel.filter({username : 'selim'}).run().then(function(result){
    myResult = result;
    console.log("inside callback", myResult); // write result
});
console.log("outside callback", myResult); // do not write

you will see that in the console:

"outside callback" undefined
"inside callback" myResultValue

However, if what you want is to reuse the value of my result somewhere else, Then you need to callback another method after the execution completes. You will need to do something like:

var otherMethod = function(data){
   console.log(data);
};

  var myResult;
    UserModel.filter({username : 'selim'}).run().then(function(result){
        myResult = result;
        console.log("inside callback", myResult); // write result
        otherMethod(myResult);

    });

This way, you should see the correct result in otherMethod

QuantumLicht
  • 2,103
  • 3
  • 23
  • 32
  • Can you provide a bit more context about what you are trying to do ? Remember that node is fully asynchronous, so it rare that you want to reuse values outside of a callback, like you are doing, because you never know when it's going to be available. – QuantumLicht Nov 29 '14 at 23:15
  • Yes otherMethod is working. thanks @QuantumLicht, but I can not assign to the variable, my result – slmkrnz Nov 29 '14 at 23:46
  • @slmkrnz Please provide more details about what you are trying to do. I can't help you otherwise. – QuantumLicht Nov 29 '14 at 23:56
  • I found,http://stackoverflow.com/questions/18008479/node-js-wait-for-multiple-async-calls – slmkrnz Dec 01 '14 at 03:15