我在 Meteor 异步方法中设置了一个回调函数,以便在“可读”事件时调用。但是当 on."readed"被触发时,回调不会被调用(我知道它是从我设置的 console.log 中触发的)。
我在这里遗漏了什么吗?我已经花了几个小时了,现在正在尝试一些不同的事情!
Meteor.startup(() => {
Meteor.call("getfeed", function(feedloader) {
//I get: TypeError: undefined is not a function]
console.log(feedloader);
});
});
Meteor.methods({
getfeed: function(callb) {
var req = request('http://feeds.feedburner.com/Techcrunch');
var feedparser = new FeedParser();
testing = [];
//........a bunch of functions........
feedparser.on('readable', function() {
var stream = this
, meta = this.meta
, item;
while (item = stream.read())
{
//I'm pushing the results into testing var
testing.push(item);
}
//From the logs I can see that this is called 12 times
//but the callback's not firing!!!
console.log(testing.length);
callb(testing);
});
}
});
最佳答案
Meteor 方法不是异步函数,因为即使您在“调用”方法时传递了回调参数,它们也不会获得回调参数。相反,每个方法都在Fiber
中执行,这是处理异步代码的另一种风格。
幸运的是,Meteor 有一个很好的 helper ,可以让你混合两种风格。您需要做的是使用 Meteor.wrapAsync 包装方法代码的“纯”异步部分。这个结构应该看起来或多或少像这样:
Meteor.methods({
getfeed: function() {
var wrapped = Meteor.wrapAsync(function (callb) {
var feedparser = new FeedParser();
testing = [];
// ...
feedparser.on('readable', function() {
// probably the same code you have, but without "callb()"
});
feedparser.on('end', function () {
// NOTE: No error here, so the first argument must be null.
callb(null, testing);
})
});
// NOTE: Finally, call the wrapped function
return wrapped();
}
});
关于javascript - Meteor js 回调不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38481308/