Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor method with HTTP request does not return callback

I am trying to create a Meteor method with a HTTP get request. I am getting back a result, but I can't get my callback on the client side to return the result. The callback needs to wait for the HTTP request to get back a result before it returns the callback. I am getting the data successfully from the HTTP request, so that is not the problem.

Any suggestions on how to get this working?

Meteor.methods({
   getYouTubeVideo: function (id) {
    check(id, String);

    var params = {
        part:'snippet, status, contentDetails',
        id:id,
        key:Meteor.settings.youtube.apiKey
    };

    HTTP.get('https://www.googleapis.com/youtube/v3/videos', {timeout:5000, params:params}, function(error, result){
      if (error) {
        throw new Meteor.Error(404, "Error: " + error);
        return;
      }
        console.log(result);
        return result; 
    });
  }
});
like image 757
zero Avatar asked Feb 13 '26 04:02

zero


1 Answers

You need to use the synchronous version of HTTP.get, just like this :

var result=HTTP.get('https://www.googleapis.com/youtube/v3/videos', {timeout:5000, params:params});
return result;

If you use the asynchronous version with a callback like you did, you're facing the common problem of having to try returning the result in the callback (which won't work) instead of in the method, which is what you should do.

Note that synchronous HTTP.get is only available in the server-environment, so put your method declaration under server/

like image 133
saimeunt Avatar answered Feb 15 '26 16:02

saimeunt