Meteor从Async函数获取值

时间:2015-11-20 06:48:08

标签: meteor

我在meteor中从wrapAsync函数获取返回值时遇到问题。以下是我的代码

Template.greet.helpers({
  greet : function () {
    var convertAsyncToSync  = Meteor.wrapAsync( HTTP.get );
    resultOfAsyncToSync = convertAsyncToSync('http://www.demo.com/api/greet', {} );
    console.log(resultOfAsyncToSync);
    return resultOfAsyncToSync;
  }
});

我在控制台中获得了未定义的值。

1 个答案:

答案 0 :(得分:0)

尝试

Template.greet.onCreated(function(){
  this.apiResult = new ReactiveVar(null);
})
Template.greet.helpers({
  greet : function () {
    var t = Template.instance();
    HTTP.get('http://www.demo.com/api/greet', {}, function(e,r){
      //process response and save it in reactivevar
      t.apiResult.set(r.data);
    });
    return t.apiResult.get();
  }
});

请勿忘记添加包meteor add reactive-var

修改

Template.greet.onRendered(function(){
  var t = Template.instance();
  HTTP.get('http://www.demo.com/api/greet', {}, function(e,r){
    //process response and save it in reactivevar
    t.apiResult.set(r.data);
  });
})

Template.greet.helpers({
  greet : function () {
    var t = Template.instance();
    return t.apiResult.get();
  }
});