Sunday, 16 December 2018

Multiple Callback Functions with the Node Twitter Library

I'm trying to make requests to Twitter with Twitter for Node and store responses in an array for handling later. I'm pushing returned tweets to an array with each push() happening in a callback, which seems to be working fine. My problem is that I'm having trouble accessing the full array with all pushed tweets.

The cause, of course, is that any attempt to work with that array is getting called before the results from the Twitter API have arrived, so I'm getting an empty array.

How can I (and should I) get my function working with the full array into another callback? I'm asking this from the perspective of someone still trying to get a firm grasp on asynchronous programming - especially multiple callbacks or functions that have to run asynchronously.

Again, current result is tweetHold = [], and I'd like tweetHold to contain all matched tweets for all users in the searchArray.

let searchArray = {
  users: ['ByBuddha', 'thetweetofgod']
}

let tweetHold = [];  

let T = new Twitter(config);

for (user of searchArray.users) {

  let params = {
    q: 'from:'+ user,
    count: 1,
    tweet_mode: 'extended',
    result_type: 'recent',
    lang: 'en'
  }

  T.get('search/tweets', params, returnedTweets);

}

function returnedTweets(err, tweets, response) {
  tweetHold.push(tweets);
}

// obviously, doesn't work as the array is logged to console before T.get() is done
console.log(tweetHold);



from Multiple Callback Functions with the Node Twitter Library

No comments:

Post a Comment