Why is undefined being returned for Meteor.call() in client?

偶尔善良 提交于 2019-12-18 09:48:16

问题


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!


回答1:


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.




回答2:


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().



来源:https://stackoverflow.com/questions/31664423/why-is-undefined-being-returned-for-meteor-call-in-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!