I need to prevent my meteor helper from returning right away until either the timeout or data returns from my Meteor.http.get(url, ...)
request. For example,
Meteor.templateName.helpers ({
testHelper: function()
{
var ss = "doesnt wait";
Meteor.http.get("http://api.somesite.com",
function (error, result) {
if(!error){
if(result.statusCode === 200) {
var respJson = JSON.parse(result.content);
console.log(respJson);
ss = "should have this value";
}
}
});
return ss;
}
})
Is Meteor.http
not a blocking call, how can i make the helper method stop until the get request returns data. Do i need to move the get request to a Meteor.Method ?
On the client, you don't have the fiber module, as a result is not possible to make a synchronous call to a function. One solution might be to use a Session because of it's reactivity. You just set a default value, and use it in your helper function
Session.setDefault('testHelper', {msg: 'wait'})
Meteor.templateName.helpers ({
testHelper: function() {
return Session.get('testHelper');
}
});
Then update this session every time you want:
Template.templateName.rendered = function () {
Meteor.http.get("http://api.somesite.com",
function (error, result) {
if(!error && result.statusCode === 200){
var respJson = JSON.parse(result.content);
Session.set('testHelper', respJson)
}
}
);
}
If you don't want to use a Session
, you can implement your own reactivity mecanism using the Deps
module. For instance in the Meteor.http.get
callback you can set a Template.templateName
attribute and invalidate a context object in order to rerun the helper function. But a Session is definitly more easy ;-)