Meteor method with HTTP request does not return callback
I am trying to create a Meteor method with an HTTP get request. I am returning a result, but I cannot get a client side callback to return the result. The callback must wait for the HTTP request to return a result before it returns the callback. I am receiving data successfully from an HTTP request, so this is not a problem.
Any suggestions on how to do this?
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;
});
}
});
source to share
You need to use the synchronous version HTTP.get
like this:
var result=HTTP.get('https://www.googleapis.com/youtube/v3/videos', {timeout:5000, params:params});
return result;
If you are using the asynchronous version with a callback like you are, you run into a common problem trying to return the result in a callback (which won't work) and not in a method, which is what you should be doing.
Note that synchronous HTTP.get
is only available in the server environment, so place the method declaration inserver/
source to share