josiahgoff
josiahgoff

Reputation: 13

Why is my Meteor app logging to server but not client?

I'm building a meteor app that hooks into the twitter api and I've had no luck so far getting it to work. I'm using the twit package to make the call on the server side, and it logs the data to the server console, but when the client console goes to log it there is no data.

The client doesn't throw an error, it runs the console.log in the else statement for the result parameter, but it comes through as undefined. It's as if the result callback runs before the data comes back, but my understanding of the Meteor.call method is that it's supposed to wait until it hears back from the server before it runs.

What am I doing wrong here?

if (Meteor.isClient) {
  Template.hello.greeting = function () {
    return "Welcome to testing.";
  };

  Template.hello.recentFollows = function () {
    return Session.get("recentFollows");
  };

  Template.hello.events({
    'click #fetchButton': function () {

        console.log("Recent tweets from stream!");

        userName = "josiahgoff";

        Meteor.call('getBananaTweets', function(err, result) {
            if(err) {
                console.log("error occurred on receiving data on server. ", err);
            } else {
                console.log("result: ", result);
                Session.set("recentFollows", result);
            }
        });

    }
  });
}

if (Meteor.isServer) {
    Meteor.startup(function () {
        Twit = new TwitMaker({
            consumer_key:         '******',
            consumer_secret:      '******',
            access_token:         '******',
            access_token_secret:  '******'
        });
    });

    Meteor.methods({
        getBananaTweets: function () {
            Twit.get('search/tweets', { q: 'banana since:2011-11-11', count: 1 }, function(err, result) {
                if (err) {
                    console.log("Error", err);
                    return err;
                } else {
                    console.log(result);
                    return result;
                }
            });
        }
    });
}

Upvotes: 0

Views: 144

Answers (1)

Christian Fritz
Christian Fritz

Reputation: 21364

You are using return in your server code in a place where it must not be used: in an asynchronous call-back. The Twit.get call returns immediately and the function ends (with no return value). So the client doesn't receive anything. Some time later the Twit.get comes back, but the return in that case goes nowhere.

This is a pretty common question. The solution is to wrap your Twit.get call into a fiber in some shape or form to make it synchronous. See for instance this answer: Iron Router Server Side Routing callback doesn't work

Upvotes: 1

Related Questions