I am trying to get json data from one API using Meteor Method, I have tried to use meteor wrapAsync as well as Node Future. Below is my code:
Template Helper - Client Side
getLocationTimebyAPI: function (company_location) {
Meteor.call('getLocationTimebyAPIServerMethod', company_location, function(error, results){
if(error){
console.log('error',error.reason);
} else {
var localtime = results.data.data.time_zone[0].localtime
var utcoffset = results.data.data.time_zone[0].utcOffset
console.log(localtime+ ' '+utcoffset);
var returntext = localtime+' (UTC '+utcoffset+')';
return returntext;
}
});
}
Method 1: Using Meteor wrapAsync - Server Side
'getLocationTimebyAPIServerMethod': function(company_location){
var apiurl = 'http://api.worldweatheronline.com/free/v2/tz.ashx?q='+company_location+'&format=json&key=XXXXXX';
var convertAsyncToSync = Meteor.wrapAsync( HTTP.get ),
resultOfAsyncToSync = convertAsyncToSync( apiurl );
return resultOfAsyncToSync;
}
Method 2: Using Node Fiber Future- Server Side
'getLocationTimebyAPIServerMethod': function(company_location){
// use the node fibers npm
var Future = Npm.require('fibers/future');
var apiurl = 'http://api.worldweatheronline.com/free/v2/tz.ashx?q='+company_location+'&format=json&key=XXXXXXXX';
// Create our future instance.
var future = new Future();
HTTP.get( apiurl, {}, function( error, response ) {
if ( error ) {
future.return( error );
} else {
future.return( response );
}
});
return future.wait();
}
In Both the methods, I am getting the values printed in the console but they are not getting returned.
I don't know where I am wrong, Could anyone please suggest me something.
Edited : Added Template Code:
<tr>
<td>Local Time:</td>
<td><input id="company_location_time" name="company_location_time" type="text" size="23" placeholder="Lead Company Location Time" value="{{getLocationTimebyAPI company_location}}" readonly style="background:#7FAAFF;font-weight:bold;"><p style="font-size:8px;">Local Time Powered By <a style="font-size:8px;" href="http://www.worldweatheronline.com/search-weather.aspx?q={{company_location}}" target="_blank">World Weather Online</a></p></td>
</tr>
From what the docs say, you can just omit the async-callback and it will run synchronously. So this should work on the server:
'getLocationTimebyAPIServerMethod': function(company_location){
// do checks
var apiurl = 'http://api.worldweatheronline.com/free/v2/tz.ashx?q='+company_location+'&format=json&key=XXXXXX';
var result = HTTP.get( apiurl );
return result;
}
On the client, the template helper should return undefined
since when the helper is called there is no return value, yet. And there is no reactive data source in the helper that would cause the template to rerender. So, either use a reactive-var
to store your result or use this package from stubailo meteor-reactive-method.
Let me know if that solves your issue!