Accessing parameters in callbacks


#1

On the client I have the following code that’s supposed to get tweets from the server:

Meteor.call('twitter.tweets', userArea(), function(error, tweets) {
      console.log(tweets);
    });

On the server I have tried this code:

'twitter.tweets'(userArea) {
      let twit = require('twit')
      let twitter = new twit({ });

      var hash; 

      twitter.get('search/tweets', { q: '#' + userArea, result_type: 'popular', count: 15 }, function(error, tweets) {
      hash = tweets;
      console.log(hash) // displays tweets
      });

      console.log(hash) // doesn't display tweets

}

I need the tweets that are available in the callback, but they aren’t available out of the callback. I have also tried using a function with this and assigning the tweets to this, although that doesn’t work either.

'twitter.tweets'(userArea) {
      let twit = require('twit')
      let twitter = new twit({ ... });

      function hash (error, tweets) {
        if(error) console.log(error)
        this.tweets = tweets;
        console.log(this.tweets);
      }

      var hashes = new hash(null, 'none');
      let twitter = new twit({ });

      twitter.get('search/tweets', { q: '#' + userArea, result_type: 'popular', count: 15 }, hashes);
      console.log(hashes.tweets); // displays object of tweets as 'none'

      return hashes;
}

This doesn’t work either. What would be the best approach and what would fix it?


#2

You need to wait for the results of your tweets function. Check out Meteor.wrapAsync


#3

I coded my application as such:

var hash = Meteor.wrapAsync(twitter.get);
var tweets = hash('search/tweets', { q: '#' + userArea, result_type: 'popular', count: 15 });

I wrapped the function and I have the following error, this.request is not a function at Twitter.get (/node_modules/twit/lib/twitter.js:64:15).


#4

Because the context of this is different in your hash function. Maybe declare var method = this and use method.tweets in your hash function?


#5

You likely want var hash = Meteor.wrapAsync(twitter.get, twitter); to preserve the context expected by twitter.get().