Skip to content Skip to sidebar Skip to footer

How To Return From Remote Api Call In Meteor Method?

I have a call to API from meteor method. How can I return the data to the client? I have no success as seen below: Meteor.methods({ 'geCoordinates': function(distance,location)

Solution 1:

There is another way to achieve this with a nice syntax using Promise. It seems that there are not many people aware that Meteor methods play nicely with Promise. Here is how to do it:

Meteor.methods({
  'geCoordinates': function(distance, location) {
    return geocoder.geocode(location).then((data) => {
      lat = data.results[0].geometry.location.lat;
      lng = data.results[0].geometry.location.lng;
      return'http://localhost:3005/events?lat=' + lat + '&lng=' + lng + '&distance=' + distance + '&sort=venue&accessToken=1048427405248222|u4dBjiRw-9gdsgml1puWYFGrEvw';
    }).catch((err) => {
      console.log("See on error " + err);
      throw err;
    });
  }
})

Solution 2:

You can use Npm future to return data synchronously , Using Npm you code will be look something like this

On server side

var future = require('future');

Meteor.methods({
'geCoordinates': function(distance,location) {
    this.unblock();
    var fut = newFuture();
    geocoder.geocode(location, function ( err, data ) {
        if (err) {
            console.log("See on error " + err)
         } else {
            lat = data.results[0].geometry.location.lat 
            lng = data.results[0].geometry.location.lng
        }
            url = 'http://localhost:3005/events?lat='+lat+'&lng='+lng+'&distance='+distance+'&sort=venue&accessToken=1048427405248222|u4dBjiRw-9gdsgml1puWYFGrEvw'
     fut.return(url); // returns the url
    })
return fut.wait(); // waits until the url is ready
}

})

Note: This will return data synchronously.

Post a Comment for "How To Return From Remote Api Call In Meteor Method?"