我正在学习流星编写一个简单的应用程序来从一个集合中提取信息(一组,并基于从该集合返回的内容(项目、名称和项目 ID 的大列表),在不同的集合中查找一个项目名称。我的想法是项目集合只在服务器上发布,因为它很大并且客户端不需要直接访问它。
一切或多或少都有效,除了我认为我没有正确处理回调。这是我写的简单测试。我传递项目名称的模板:
Template.operations.getTypeID = function(name) {
result = "";
console.log("Precall Logging name: ", name);
console.log("Precall Logging result: ", result);
result = Meteor.call('getID', name, function (error, result) {
console.log("Async Logging in call: result: ", result);
});
console.log("Name is now", name);
console.log("Result is now", result);
return name;
}
这是服务器上的方法,我最终将在其中根据名称查找 ID:
Meteor.methods({
getID: function(itemName) {
result = itemName + "_changed";
console.log("server: getID result:", result);
return result;
}
});
这里是我在 HTML 文件中调用模板的地方:
<td>{{getTypeID name}}</td>
当我使用该应用程序时,我可以看到方法 getID 以一种看起来像异步的方式被调用 - getID 方法中的结果会发生变化,并在模板中的其他条目之后写入控制台。如何将回调中返回的结果设置为可在模板中使用并返回给客户端,以便我可以在页面中呈现它?
更新:这是我在进行一些编辑后的 console.log 输出:
Precall Logging name: Apples lootlog.js:79
Precall Logging result: lootlog.js:80
Name is now Apples lootlog.js:86
Result is now undefined lootlog.js:87
Precall Logging name: Oranges lootlog.js:79
Precall Logging result: lootlog.js:80
Name is now Oranges lootlog.js:86
Result is now undefined lootlog.js:87
Precall Logging name: Melons lootlog.js:79
Precall Logging result: lootlog.js:80
Name is now Melons lootlog.js:86
Result is now undefined lootlog.js:87
Precall Logging name: Grapes lootlog.js:79
Precall Logging result: lootlog.js:80
Name is now Grapes lootlog.js:86
Result is now undefined lootlog.js:87
Precall Logging name: Onion lootlog.js:79
Precall Logging result: lootlog.js:80
Name is now Onion lootlog.js:86
Result is now undefined lootlog.js:87
Async Logging in call: result: Apples_changed lootlog.js:83
Async Logging in call: result: Oranges_changed lootlog.js:83
Async Logging in call: result: Melons_changed lootlog.js:83
Async Logging in call: result: Grapes_changed lootlog.js:83
Async Logging in call: result: Onion_changed
这是打印到流星控制台的内容:
server: getID Name: Apples
server: getID result: Apples_changed
server: getID Name: Oranges
server: getID result: Oranges_changed
server: getID Name: Melons
server: getID result: Melons_changed
server: getID Name: Grapes
server: getID result: Grapes_changed
server: getID Name: Onion
server: getID result: Onion_changed