到目前为止,我已经能够从 Twitter 中提取流式实时数据。我如何使用这些数据?我正在尝试将其插入集合中,但出现此错误:
Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
我尝试用纤程包装我的代码,但它不起作用/或者我没有包装代码的正确部分。另外,我不确定这是否是在 Meteor 中使用流数据的正确方法。
Posts = new Meteor.Collection('posts');
if (Meteor.isClient) {
Meteor.call("tweets", function(error, results) {
console.log(results); //results.data should be a JSON object
});
}
if (Meteor.isServer) {
Meteor.methods({
tweets: function(){
Twit = new TwitMaker({
consumer_key: '...',
consumer_secret: '...',
access_token: '...',
access_token_secret: '...'
});
sanFrancisco = [ '-122.75', '36.8', '-121.75', '37.8' ];
stream = Twit.stream('statuses/filter', { locations: sanFrancisco });
stream.on('tweet', function (tweet) {
userName = tweet.user.screen_name;
userTweet = tweet.text;
console.log(userName + " says: " + userTweet);
Posts.insert({post: tweet})
})
}
})
}
最佳答案
改变数据库的代码需要在纤程中运行,这就是错误所在。在 Meteor 以外的库的回调中运行的代码不会(必然)在纤程中运行,因此您需要包装回调函数以确保它在纤程中运行,或者至少是它的一部分与数据库交互。
Meteor.bindEnvironment 目前没有记录,但它通常被认为是包装回调的最可靠方法。错误所说的Meteor.bindEnvironment定义在这里供引用:
https://github.com/meteor/meteor/blob/master/packages/meteor/dynamics_nodejs.js#L63
这样的事情可能是完成这项工作的最简单方法:
tweets: function() {
...
// You have to define this wrapped function inside a fiber .
// Meteor.methods always run in a fiber, so we should be good here.
// If you define it inside the callback, it will error out at the first
// line of Meteor.bindEnvironment.
var wrappedInsert = Meteor.bindEnvironment(function(tweet) {
Posts.insert(tweet);
}, "Failed to insert tweet into Posts collection.");
stream.on('tweet', function (tweet) {
var userName = tweet.user.screen_name;
var userTweet = tweet.text;
console.log(userName + " says: " + userTweet);
wrappedInsert(tweet);
});
}
关于javascript - 在 Meteor 中使用来自 Twitter 的流数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21919794/