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;
});
}
});
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With