我试图在异步流星方法的回调中传递一个值。 “mongoCollections”是全局变量
// Async method
let waiter = function(cb) {
setTimeout(() => {
cb(undefined, {data: 'test', other: mongoCollections})
}, 1000);
}
// Meteor method
Meteor.methods({
'getCollections': () => {
let func = Meteor.wrapAsync(waiter);
let res = func();
return res;
}
});
在客户端
Meteor.call('getCollections', (err, res) => {
console.log(err, res)
});
问题在于,在当前状态下,不会触发客户端回调,也不会发生错误或任何错误。
但是如果删除对象的“other:mongoCollections”部分,则会触发回调。为什么发送mongoCollections会阻止回调被触发?如果有错误我怎么能抓住它?
答案 0 :(得分:0)
我的猜测是,您在waiter()
和cb()
的执行之间丢失了上下文,这意味着mongoCollections
中cb()
未定义,因此调用失败。
尝试在您mongoCollections
的匿名函数中记录setTimeout
。它可能会显示为undefined
。
或者像这样试试:
let waiter = function(cb) {
var _mongoCollections = mongoCollections;
setTimeout(() => {
cb(undefined, {data: 'test', other: _mongoCollections})
}, 1000);
}
(将mongoCollections放入闭包instsead)
另一种可能性(基于下面的评论):您的mongoCollections对象不可序列化。您可以通过记录JSON.stringify(mongoCollections)
的结果来尝试。如果失败,您必须提取所需对象的部分,可以序列化。
答案 1 :(得分:0)
这里可能会发生很多事情,但我的猜测是错误正在某处发生,并且错误消息会被更深层次的处理程序吞噬。
您可能希望至少使用Meteor.setTimeout
而不是香草setTimeout
。看看这里:http://docs.meteor.com/api/timers.html#Meteor-setTimeout
除此之外,我会遵循之前的回答者的建议,并尝试确保mongoCollections与您认为的一样全球化。如果回调工作和不工作之间的唯一变化是添加单个符号,那么罪魁祸首可能是您添加的符号未定义。