在方法中返回 Meteor.http 结果 [英] Return Meteor.http results in method

查看:11
本文介绍了在方法中返回 Meteor.http 结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个环绕 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(method, url [, options] [, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆