Meteor Async from server to client

Sometime you want to do async call from api and make call or reactive on the client side, so how do you do it?
first create a method on server side, I would always recommend using methods rather allow / denied from client side, lets give a method name asyncMethods

 

// Server side
Meteor.methods({
  asyncMethods: function(){
    var url = "http://example.net/api/" // your api url
    HTTP.get(url, function(err, res){
      if(err){
        throw new Meteor.error('apiError', err.reason);
      } else {
       console.log(res);
      }
    })
  }
})

 

Ok now run this client side method call

// Client side
Meteor.call('asyncMethods', function(err, res){
  console.log(res);
})

you will notice 2 things, on your console.log for client will become undefined, and on server side log you properly see some results.
so lets say you want to return result after api was called, meteor provided a very helpful method call Meteor.wrapAsync(), which basically returns your async call to synchronous call, so you could call it from client side, change your server code to this:

 

// Server side
Meteor.methods({
  asyncMethods: function(){
    var url = "http://example.net/api/" // your api url

    function asyncCall(){
      HTTP.get(url, function(err, res){
        if(err){
          throw new Meteor.error('apiError', err.reason);
        } else {
          return res;
        }
      })
    }
    var syncCall = Meteor.wrapAsync(asyncCall);
    var res = syncCall();

    // now you can return the result to client.
    return res;
  }
})