返回Meteor.http结果的方法 [英] Return Meteor.http results in method
问题描述
我有一个包围http.get的Meteor方法。我试图将http.get的结果返回到方法的返回中,以便在调用方法时可以使用结果。
我无法使其工作。
I have a Meteor method that wraps around an http.get. I am trying to return the results from that http.get into the method's return so that I can use the results when I call the method.
I can't make it work though.
这是我的代码:
(在共享文件夹中)
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;
}
});
出于某种原因,即使它们存在且http调用,也不会返回结果工作: console.log(result.content); 确实记录了结果。
For some reason, this does not return the results even though they exist and the http call works: console.log(result.content); does indeed log the results.
(客户端文件夹)
Meteor.call('getWeather', somezipcode, function(error, results) {
if (error)
return alert(error.reason);
Session.set('weatherResults', results);
});
当然,会话变量最终为空。
(请注意,如果我在方法中使用一些虚拟字符串对返回进行硬编码,则代码的这一部分似乎没有问题。)
Of course here, the session variable ends up being empty.
(Note that this part of the code seems to be fine as it returned appropriately if I hard coded the return with some dummy string in the method.)
帮助?
推荐答案
在你的例子中 Meteor.http.get
是异步执行。
In your example Meteor.http.get
is executed asynchronously.
查看文档:
HTTP.call(方法,网址[,选项] [,asyncCallback])
在服务器上,此功能可以同步运行,也可以异步运行
。如果省略回调,它将同步运行,并且
请求成功完成后返回结果。如果
请求未成功,则抛出错误
On the server, this function can be run either synchronously or asynchronously. If the callback is omitted, it runs synchronously and the results are returned once the request completes successfully. If the request was not successful, an error is thrown
通过删除asyncCallback切换到同步模式:
Switch to synchronous mode by removing asyncCallback:
try {
var result = HTTP.get( weatherUrl );
var weather = result.content;
} catch(e) {
console.log( "Cannot get weather data...", e );
}
这篇关于返回Meteor.http结果的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!