callback - 如何让 Meteor.Call 返回模板值?

标签 callback meteor

我已经尝试过to understand this post regarding this concept ,但是,我没能得到它。我有以下简单的设置:

/server/test.js
Meteor.methods({ 
  abc: function() {
    var result = {};
    result.foo = "Hello ";
    result.bar = "World!";
    return result;
  }
});

/client/myapp.js
var q = Meteor.call('abc');
console.log(q);

此结构返回到控制台未定义

如果我将 myapp.js 文件更改为:

Meteor.call('abc', function(err, data) {
  !err ? console.log(data) : console.log(err);
}

我在控制台中收到对象

理想情况下,这是我想要做的,但它不起作用,在控制台中指出:无法读取未定义的属性“问候”

/client/myapp.js
var q = Meteor.call('abc');

Template.hello.greeting = function() {
   return q.foo;
}

任何将数据从服务器对象传递到模板的帮助将不胜感激。我仍在学习 JavaScript 和 Meteor。

谢谢!

最佳答案

来自the Meteor.call documentation :

On the client, if you do not pass a callback and you are not inside a stub, call will return undefined, and you will have no way to get the return value of the method. That is because the client doesn't have fibers, so there is not actually any way it can block on the remote execution of a method.

所以,你会想这样做:

Meteor.call('abc', function(err, data) {
  if (err)
    console.log(err);

  Session.set('q', data);
});

Template.hello.greeting = function() {
  return Session.get('q').foo;
};

一旦数据可用,这将 react 性地更新模板。

关于callback - 如何让 Meteor.Call 返回模板值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10677491/

相关文章:

javascript - 将变量传递给函数回调

csv - 使用node-csv和meteor-file将CSV导入到集合中

javascript - img src 中的 meteor 模板不起作用

javascript - ReactJS 与传单 : tiles not correctly displayed until page refresh

java - 不同类android java中的Paho-mqtt回调

javascript - 局部变量在 javascript 的回调函数中变得未定义

javascript - 有没有一个函数可以测试一个在js中有回调的对象实例?

jquery - 在jquery中调用两个用户定义的函数

security - 如何使用 check 防止恶意 Meteor 订阅

meteor - 如何从 Meteor.methods 函数返回错误