Search code examples
javascriptasynchronousmeteor

Make Meteor method synchronous


I've been attempting to make this function synchronous. I've read several Stack Overflow posts about Async but I'm unable to comprehend how I would be able to make this synchronous. As of now, it is asynchronous therefore it returns undefined before heading into the callback function.

I call it from the client side:

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

And this is the server side method:

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

I'm using the Twitter API and what I want to do is basically retrieve the screen name from the JSON and return it to a variable on the client side. But this is returning undefined because the callback is being compiled after the compiler has reached the end of the 'screenName' function.

I want it to return the value from the callback function but reading up other examples has not helped me comprehend how I can transform my code. I need to make this function synchronous but I don't know how to do it.


Solution

  • Simply use Meteor.wrapAsync to turn your asynchronous T.get into a synchronously styled one!

    It won't actually get executed in a pure "synchronous" way though, it is using a trick known as a Fiber, but you should read the docs to learn more.
    Here goes:

    var Tget = Meteor.wrapAsync(T.get);
    
    Meteor.methods({
      'screenName': function() {
        return Tget({
          q : '#UCLA',
          count : 1
        }).status[0].user.screen_name;
      }
    });