Why is undefined being returned for Meteor.call()

2020-02-15 08:43发布

So I'm attempting to access the twitter REST API and retrieve the screen name of a tweet. I feel like my code will be better explanation:

I'm calling the method 'screenName' from the isClient() :

  'click button': function () {
    Meteor.call('screenName',
      function(error,result) {
        if (error) {
          console.log(error);
        }
        else {
          window.alert(result);
        }
      }
    )
  }

And for some reason the method returns undefined when its actually logging in the screen name of the twitter account on the console.

Meteor.methods({
  'screenName': function() {
      T.get('search/tweets',
      {
        q:'#UCLA',
        count:1
      },
      function(err,data,response) {
        console.log(data.statuses[0].user.screen_name);
        return data.statuses[0].user.screen_name;
      }
    )
  }

If someone could please help me with this. Thank you so much!

2条回答
\"骚年 ilove
2楼-- · 2020-02-15 08:56

You are only returning data.statuses[0].user.screen_name from your inner function. You need to return it from your screenName method to have it available in Meteor.call().

查看更多
女痞
3楼-- · 2020-02-15 09:14

Your server method needs to be synchronous. The callback in the method is returning after the method has already returned undefined. I'd like to be more specific but I'm not sure what library you are using.

You can get a feel for this by looking at the examples from the HTTP.call documentation. Your code could look something like this:

Tget = Meteor.wrapAsync(T.get);

Meteor.methods({
  'screenName': function() {
    try {
      var result = Tget('search/tweets', {q:'#UCLA', count:1});
      return result.statuses[0].user.screen_name;
    } catch (e) {
      return false;
    }
  }
});

See the docs for more information on wrapAsync.

查看更多
登录 后发表回答