0

I trigger a function using require() in my app.js file and the result returned is 'undefined'. I think this is due to the function being nested. What is the best way to return the nested value. I have tried the method below but the function appears to be asynchronous and the returned value is returned as undefined before the data is provided.

app sample code --

app.get("/twitter/:handle", function (req, res) {

    var handle = req.params.handle;
    var twitter = require('./module/twitter');
    var data = twitter.searchHandle(handle);

    console.log(data);
    res.sendStatus(data);

});

module sample code -

var twitter = {
 searchHandle: function(handle){
      
        var dataToReturn;
        
  T.get('search/tweets', { q: handle, count: 100 }, function(err, data, response) {
   dataToReturn = data;
          
  });
        
        return(dataToReturn);
        
 }
};

module.exports = twitter;
Vitalii Zurian
  • 17,858
  • 4
  • 64
  • 81
jstleger0
  • 105
  • 1
  • 14
  • The `dataToReturn` hack cannot work, the whole reason for `T.get` even taking a callback instead of just returning the value directly is because it's asynchronous. If it was synchronous it would directly return the value to you in the function call. – Esailija Jan 30 '15 at 14:45

1 Answers1

0

searchHandle is an async call. Returning dataToReturn will always be undefined as it's value has not yet been populated. You will need to pass a callback function to searchHandle to be executed once dataToReturn is populated.

//app.js
var handle = req.params.handle;
var twitter = require('./module/twitter');
var data = twitter.searchHandle(handle, function (data) {
    console.log(data);
    res.sendStatus(data);
});

//twitter.js
var twitter = {
    searchHandle: function(handle, callback){

        T.get('search/tweets', { q: handle, count: 100 }, function(err, data, response) {
            callback(data);
        });

    }
};

module.exports = twitter;
KJ Price
  • 5,774
  • 3
  • 21
  • 34
  • Hello thanks for the reply. The "console.log" was returning the correct data. And a callback or promise does makes sense. However the function when ran from app.js "i.e. twitter.searchHandle(handle)" returned undefined. This problem still exists with the addition of a callback doesn't it? – jstleger0 Jan 30 '15 at 14:32
  • If the console.log returned the correct data then it is working. I suggest you read up on async callbacks in javascript. It takes some getting used to and, for the most part, you will have to retrain yourself to see which functions will require a callback. The "problem" (as you said) is not actually a problem but an intended aspect of nodejs architecture. The method `searchHandle` will always (and should) return `undefined` unless it is a promise. – KJ Price Jan 30 '15 at 14:52