在使用Meteor进行异步服务器端调用时,如何使助手函数响应?

在使用Meteor进行异步服务器端调用时,如何使助手函数响应?,meteor,Meteor,下面是我的HTML、客户端和服务器JS。我遇到的问题是,首先我的helper函数不返回任何内容,因为服务器调用需要一秒钟才能返回数据 我需要的是,当数据最终在helper函数中返回给客户机时,HTML可以进行更新 HTML 客户端JS Template.matches.helpers({ matches: function() { Meteor.call('callAuthorize', function(error, response){

下面是我的HTML、客户端和服务器JS。我遇到的问题是,首先我的helper函数不返回任何内容,因为服务器调用需要一秒钟才能返回数据

我需要的是,当数据最终在helper函数中返回给客户机时,HTML可以进行更新

HTML

客户端JS

    Template.matches.helpers({
    matches: function() {
        Meteor.call('callAuthorize', function(error, response){
            return response.matches;
        })
    },
服务器JS

Meteor.methods({

    callAuthorize: function () {
        //load Future
        Future = Npm.require('fibers/future');
        var myFuture = new Future();
        //call the function and store its result
        client.authorize(
            "FB_Auth",
            "FB_Id",
            function () {
                client.getHistory( function (error, data) {
                    myFuture.return(data);
                });
            })
        return myFuture.wait();
    }
});
}

你有几个选择。例如,您可以将方法的结果存储在会话变量中,并返回此变量:

if (Meteor.isClient) {
  Meteor.call('callAuthorize', function(error, response){
    Session.set('authorizeMatches') = response.matches;
  });

  Template.matches.helpers({
    matches: function() {
      return Session.get('authorizeMatches');
    }
  });
}

或者,使用:


您还可以使用该软件包:


当然,在这两个选项中,您的助手永远不会自行更新:只有订阅/发布可以让客户端知道其数据何时更新,而方法不会这样做。如果你想让你的方法重复facebook API调用,你必须使用轮询。例如:

Meteor.setInterval(function() {
  Meteor.call('callAuthorize', function(error, response){
    Session.set('authorizeMatches') = response.matches;
  });
}, 5000); // every 5 seconds

例如,在onRendered函数中进行调用,并将来自调用的响应附加到某个可在helper中返回的被动变量
  Template.matches.onCreated(function() {
    this.authorizeMatches = new ReactiveVar;
    Meteor.call('callAuthorize', function(error, response){
      this.authorizeMatches.set(response.matches);
    });
  });

  Template.matches.helpers({
    matches: function() {
      return Template.instance().authorizeMatches.get();
    }
  });
Template.matches.helpers({
  matches: function() {
    var result = ReactiveMethod.call('callAuthorize');
    return result.matches;
  }
});
Meteor.setInterval(function() {
  Meteor.call('callAuthorize', function(error, response){
    Session.set('authorizeMatches') = response.matches;
  });
}, 5000); // every 5 seconds