【问题标题】:Meteor methods returning undefined on client even after using callback即使在使用回调之后,Meteor 方法也会在客户端返回未定义
【发布时间】:2018-09-06 15:53:06
【问题描述】:

我正在尝试使用服务器上的流星方法从 AirVisual API 获取数据并将其传递给客户端。数据在服务器上成功接收。但是,当在其中调用方法时,模板助手会变得未定义。

客户端助手:

Template.index.helpers({  
   getCityDataOnClient: function(city, state) { 

       Meteor.call('getCityData', city.toLowerCase(), state.toLowerCase(), function(error, result) {

        if(!error) {
            console.log(result); //returns undefined


        }
        else {
            console.log(error);
        }
     });


  } 
});

lib 文件夹中的 Meteor methods.js:

Meteor.methods({
getCityData : function(city, state) {
var data = [];
const result = HTTP.call('GET', 'http://api.airvisual.com/v2/city', {

params: {
    state: state,
    city : city,
    country: 'pakistan',
    key: 'xxxxxxxxxx'

}

}, function(err, res) {
    if (!err) {

       data = res.data.data;


     //console.log(data); //prints correct data on the server and client
     return data;


    }
    else {
        console.log(err);
        return err;
    }
        });
    }
});

我已经查找过类似问题的答案。似乎没有任何工作,包括 Tracker、reactive-var 和 reactive-methods。

【问题讨论】:

标签: meteor methods server callback client


【解决方案1】:

这里的问题是您试图从回调内部将数据返回到一个函数,该函数 1. 没有在等待您,而 2. 已经返回。

值得庆幸的是,Meteor 在服务器上做了一些魔术,使像 HTTP.call 这样的异步调用看起来是同步的。 你的方法可以这样做:

Meteor.methods({
    getCityData : function(city, state) {
        const result = HTTP.call('GET', 'http://api.airvisual.com/v2/city', {
            params: {
                state: state,
                city : city,
                country: 'pakistan',
                key: 'xxxxxxxxxx'
            }
        });
        return result.data.data;
    }
});

通过排除 Meteor 的 HTTP 模块上的回调,Meteor 将在 Fiber 中运行它并在继续执行之前等待结果(如使用 async/await)

如果您使用第三方库处理 HTTP 请求,则需要使用 Meteor.wrapAsync 包装函数以获得在光纤中运行的好处。或者你可以将它包装在一个承诺中并从方法中返回承诺

【讨论】:

  • 现在很有意义。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
  • 2011-07-16
  • 2016-05-16
相关资源
最近更新 更多