I am trying to use the twitter API to get search results and then modify them, before displaying them on the page.
I am new to the idea of Asynchronous functions and I dont see how to run this method for several search strings and work on the results:
var results = [];
for (string in searches) {
client.get('search/tweets', {q: searches[string]}, function(error, tweets, response){
console.log(tweets); // I need to put these in an array (results) and get the next lot
});
}
analyse(results);
I need to run search/tweets several times and build up an array of the results so they can be analysed. I dont know how to do this if I have to work in the function? Putting it into a callback function would have the same problem.
4
Answers
There are basically two working parts here.
(1) Running a function on an interval and
(2) making an async call.
Run a function at an interval
The first is the ability to run a function at an interval. This can be accomplished the following way.
Make an Async Call
The second is making an asynchronous call. An asynchronous call is asynchronous because the result cannot be guaranteed to exist at the time of execution. You must perform any analysis/data manipulation inside of the async call. This is the only way to guarantee a response.
Assuming, based on your example, that
client.get()
is the asynchronous call, you would do something like this:Putting it all together:
The basic idea is this: keep track of how many search terms you are querying, and process the analysis when the last one finishes.
There are also more “modern” ways of handling async code including promises, which I encourage you to check out in your async endeavours.
For things like this I like to use Promises. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
It sounds like you’re wanting these requests to work in serial(executing one request at a time)… In pure JS, it would go something like:
However, these days, as noted by realseanp, Promises make this way cleaner(although his answer would run the requests in parallel).