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
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)
2) Make a new function to make requests by using Bluebird’s promisify method.
3) Use a aggregate Promise method to make two requests at the same time, such as
join
.Since you want to store results of both function in single object, you can use async module as a best practice.