如何 return meteor 中 helper 的 meteor call 值

how to return meteor call value in helper in meteor

我已将 id 传递给 html 的助手,我的助手是 getusername

getusername(id) {
    var username = "";
    Meteor.call("getUserName", id, function(error, result) {
        if (error) {
            console.log("error", error);
        }
        if (result) {
            console.log(result);
            username = result;
        }
    });
    return username;
}

当我记录结果时,它会记录我需要的内容,但在 UI 中看不到用户名。 当我将它与 Reactive var 一起使用时,它变成无穷大......因为当反应变量值改变时它再次执行......

由于异步行为,您不会获得 return 值您可以做的是在会话中设置 return 值,然后从会话中获取它

getusername(id) {
    var username = "";
    Meteor.call("getUserName", id, function(error, result) {
        if (error) {
            console.log("error", error);
        }
        if (result) {
            console.log(result);
            username = result;
        }
    });
    Session.set('getUserNameResult', result);
}

不能从同一个helper异步获取数据和return,因为helper return调用完成前没有反应变量表示数据已经改变一次呼叫完成。您使用 ReactiveVar 是正确的,但是为了避免无限循环,您必须在模板助手之外使用 运行 Meteor.call。我建议在模板的 onCreated 挂钩中执行此操作:

Template.x.onCreated(function() {
  var self = this;
  Meteor.call("getUserName", this.data.id, function(error, result) {
    if (result) {
        self.username = new ReactiveVar(result);
    }
  });
});

Template.x.helpers({
  getUserName(id) {
    return Template.instance().username.get();
  }
});

但是请注意,在几乎所有情况下,最好直接在前端执行诸如 return Meteor.users.findOne(id).profile.name 之类的获取用户名之类的操作,因为这是反应式的并且更容易。