Reputation: 8039
I am very new to meteor and I have a method in Meteor.methods
like :
sendStory(story) {
HTTP.call("GET", "https://offline-news-api.herokuapp.com/stories", function(error, response){
if(error){
console.log("error")
}else{
console.log(response)
var story = story
return story
}
})
}
and then I am calling this on my cliet like:
Meteor.call('sendStory', this.story, function(res){
console.log("some story")
console.log(res)
})
Here it is not printing the res
value it is giving undefined
and the api call is made at last..
How can I make api call first and then go to callback
from api
Thank you ..
Upvotes: 0
Views: 113
Reputation: 36
Like guns mentioned, you are returning undefined from server method. The method doesn't wait for the asynchronous function to terminate. Instead it returns.
In the server, I always go with synchronous approach.
Upvotes: 0
Reputation: 106
You could use a Future:
sendStory(story) {
Future = Npm.require('fibers/future');
var apiFuture = new Future();
HTTP.call("GET", "https://offline-news-api.herokuapp.com/stories", function(error, response){
if(error){
console.error("Error: ", error);
apiFuture.throw(error);
}else{
console.log("Response: ", response);
apiFuture.return(response);
}
});
return apiFuture.wait();
}
and on the client:
Meteor.call('sendStory', this.story, function(err, res){
console.log("some story");
if (err) {
console.error(err);
} else {
console.log("Great! A response from the API: ", res);
}
});
Upvotes: 0
Reputation: 2728
Well,
dont use the callback for http call like this:
sendStory(story) {
var story = HTTP.call("GET", "https://offline-news-api.herokuapp.com/stories");
return story;
}
refer here to Meteor Docs
You cannot return from a callback since Meteor methods run within fibers.
Upvotes: 1