skip to Main Content

I am working with the twitter api trying to get both tweets and mentions of a particular user however i am only able to get one particular set of tweets at a time. According to a similar question i have seen, a call back function would be needed to solve this problem however i am struggling as i am fairly new to node.js. My problem is i have two client.gets for tweets and mentions but i can only call one at time hence a call back function is needed.

 jsonx = {};
  function mentions(x){
    client.get('search/tweets', {q:"@"+x, count:1},
    function (err,data){
      for(var index in data.statuses){
        var tweet = data.statuses[index];
        console.log(tweet.text);
        jsonx[index] = tweet
      }
      res.end(JSON.stringify(jsonx))
    })
  }


  function tweets(y){
    client.get('statuses/user_timeline', {screen_name:"@"+y, count:1},
    function(err,data) {
      for(var index in data){
        var tweet = data[index];
        console.log(tweet.text);
        jsonx[index] = tweet

      }
           res.end(JSON.stringify(jsonx));
    })
  }

Any help on how i can implement the call back function in order to get all the queries from tweets and mentions at the same time.

Thank you
Steve

2

Answers


  1. Using a twitter client that uses Promises, or even just ‘Promisifying’ the library you have now would make this really easy.

    I recommend Bluebird.js to do this. If you were to go that route, this is how it would work:

    1) Require the promise library (after installing via npm)

    var Promise = require('bluebird');
    

    2) Make a new function to make requests by using Bluebird’s promisify method.

    var clientGet = Promise.promisify(client.get, client);
    

    3) Use a aggregate Promise method to make two requests at the same time, such as join.

    Promise.join(
        clientGet('search/tweets', {q:"@"+x, count:1}),
        clientGet('statuses/user_timeline', {screen_name:"@"+y, count:1}),
        function(tweets, timeline) {
            //other stuff here, including res.end/json/send/whatever
        }
    )
    
    Login or Signup to reply.
  2. Since you want to store results of both function in single object, you can use async module as a best practice.

    var async = require('async');
    
    async.series([
      function(_cb){
        //call function 1 here and fire _cb callback
      },
      function(_cb){
        //call function 2 here and fire _cb callback
      }
    ], function(error, response) {
      if(e) {
        //handle error
      }
      else {
        //handle response object here. It will be an array of responses from function_1 and function_2
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search