Asynchronous callbacks in the meteor application

I use the ntwitter node.js module to access the twitter streaming API from inside the meteor application, but when I try to insert a callback function into the collection inside the application, it will work:

twitter.stream('statuses/filter', {'track':'whatever'}, function(stream) { stream.on('data', function (data) { //logging the data coming back works fine console.log(data); //the next line throws "Error: Meteor code must always run within a Fiber" Tweets.insert(data); }); }); 

Is there a recommended approach for using asynchronous callbacks in the context of the Meteors linear execution model? I tried to wrap the insert inside a new Fiber, which seems to work, but I'm not sure about any consequences that might have.

I found this http://gist.io/3443021 that was useful, but I'm still not sure which approach is right for my particular case, so any help would be appreciated.

Greetings

+4
source share
2 answers

We used a different design template. In the async callback, we act more like a device driver and simply buffer the result in memory:

 var tweets = []; twitter.stream('statuses/filter', {'track':'whatever'}, function(stream) { stream.on('data', function (data) { //logging the data coming back works fine console.log(data); //the next line throws "Error: Meteor code must always run within a Fiber" tweets.push(data); }); }); 

and then later, back to the normal Meteor runtime inside Fiber, either in the timer or as a result of the function, we reset the array of tweets and paste. The Javascript array doesn't care if it works in Fiber or not.

In our case, we do this with asynchronous IMAP email, not with tweets, but the analogy still holds.

0
source

Wrap your callback in Meteor.bindEnvironment as follows:

 twitter.stream('statuses/filter', {'track':'whatever'}, function(stream) { stream.on('data', Meteor.bindEnvironment(function (data) { //logging the data coming back works fine console.log(data); //the next line throws "Error: Meteor code must always run within a Fiber" Tweets.insert(data); })); }); 

According to this SO post about Async wrappers on Meteor Server , you want to use Meteor.bindEnvironment when you control the callback using a third-party api / npm module (which looks like this)

Meteor.bindEnvironment creates a new fiber and copies the current fiber variables and environment into the new fiber.

0
source

All Articles