0

I am trying to get data from a function in a node module, that returns a json object, and show the json object in a router in my server.js file.

I am trying to export it like this:

    // Export the function
    exports.getTweets = function() {
        var tweetResult = {};
        twitter.get(
            '/statuses/user_timeline.json',
            { screen_name: 'twitter', count: 5},
            function (error, tweets) {
                tweetResult = tweets;
            }
        );
        return tweetResult;
    };

And here is my server.js file, with the route that should return the json object

tweets      = require("./twitter_stream.js"),

// set up the route for the json object
app.get("/tweets.json", function (req, res) {
    console.log(tweets.getTweets());
});

I haven't been able to get anything but an empty object.

1 Answers1

1

You need to pass a callback to the getTwitter function to receive the twitter result. The variable tweetResult is null when the code return tweetResult; is invoked.

Please check the code below to see how to use the callback in your code:

exports.getTweets = function(callback) {
        twitter.get(
            '/statuses/user_timeline.json',
            { screen_name: 'casperpschultz', count: 5},
            function (error, tweets) {
                //invoke the callback function passing the tweets  
                callback(tweets);

            }
        );
    };

Code to invoke the getTweets function passing a callback function:

app.get("/tweets.json", function (req, res) {
    //invoke getTweets passing a callback function by parameter
    tweets.getTweets(function(tweets){
         console.log(tweets);
     });
});

Node.js works in an asynchronous way with callback, here is a good reference that explains it.

Community
  • 1
  • 1
fmodos
  • 4,472
  • 1
  • 16
  • 17