我有一个包围http.get的Meteor方法.我试图将http.get的结果返回到方法的返回中,以便在调用方法时可以使用结果.
我不能让它工作.
这是我的代码:
(在共享文件夹中)
Meteor.methods({
getWeather: function(zip) {
console.log('getting weather');
var credentials = {
client_id: "string",
client_secret: "otherstring"
}
var zipcode = zip;
var weatherUrl = "http://api.aerisapi.com/places/postalcodes/" + zipcode + "?client_id=" + credentials.client_id + "&client_secret=" + credentials.client_secret;
weather = Meteor.http.get(weatherUrl, function (error, result) {
if(error) {
console.log('http get FAILED!');
}
else {
console.log('http get SUCCES');
if (result.statusCode === 200) {
console.log('Status code = 200!');
console.log(result.content);
return result.content;
}
}
});
return weather;
}
});
Run Code Online (Sandbox Code Playgroud)
出于某种原因,即使它们存在并且http调用有效,它也不会返回结果:console.log(result.content); 确实记录了结果.
(客户端文件夹)
Meteor.call('getWeather', somezipcode, function(error, results) {
if (error)
return alert(error.reason);
Session.set('weatherResults', results);
});
Run Code Online (Sandbox Code Playgroud)
当然,这里会话变量最终为空.
(请注意,如果我在方法中使用一些虚拟字符串对返回进行硬编码,则代码的这一部分看起来很好,因为它会正确返回.)
救命?
Kub*_*bek 14
在您的示例Meteor.http.get中异步执行.
查看文档:
HTTP.call(method,url [,options] [,asyncCallback])
在服务器上,此功能可以同步或异步运行.如果省略回调,它将同步运行,并在请求成功完成后返回结果.如果请求不成功,则会引发错误
通过删除asyncCallback切换到同步模式:
try {
var result = HTTP.get( weatherUrl );
var weather = result.content;
} catch(e) {
console.log( "Cannot get weather data...", e );
}
Run Code Online (Sandbox Code Playgroud)