I have two functions that query the twitter api. The query is done through a web interface and I call each function when a checkbox is on. My problem now is after all the querying has been done, I want to be able to store the data and send it back to the web interface. How do I do this ?
if (string.checktweet1 == 'on') {
tweets(string.teamname)
}
if (string.checkmentions1 == 'on'){
mentions(string.teamname)
}
if (string.checktweet2 == 'on'){
tweets(string.playername)
}
if (string.checkmentions2 == 'on'){
mentions(string.playername)
}
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);
}
})
}
My code is only sending the data for the function “tweets”
json = {};
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);
}
json[index] = tweet
res.end(JSON.stringify(json));
})
}
2
Answers
For saving the data to a file without a database, you can use fs.writeFile():
https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
Server/Node:
Client
Example taken from Socket.io docs, just modified a tiny bit http://socket.io/docs/
As I understand you are not looking to save the data, but just collect the results of multiple asynchronous calls and once all are completed deliver the data to your client? If so, you could use async or promises.
There are already examples of this in Stack Overflow, eg. this Node.js: Best way to perform multiple async operations, then do something else? but here anyways simplified implementations for both.
Using async
Using promises
I don’t know what HTTP client you are using, but you can maybe use
var client = Promise.promisifyAll(require('your-client-lib'));
to convert the methods to return promises, and then you could convert thetweets
andmentions
functions toThis way though the
results
inPromise.all
are mixed responses and you would need to identify which aretweets
and which arementions
to process them properly.