到目前为止,我已经能够从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
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); }); }