Anyone knows how can i make requests to twitter api based on text queries without using a recursion.
this is my code
function news_tweets(query, user_id, count) {
news_array = [];
user_tweets = [];
full_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id +
"&count=" + count + "&callback=?",
function (data) {
$.each(data, function (i, item) {
var user = item.user.name;
var date = item.created_at;
var profile_img = item.user.profile_image_url;
var text = item.text;
var url = (item.entities.urls.length > 0 ? item.entities.urls[0].url : '');
news_array.push({
news_user: user,
news_date: date,
news_profile_img: profile_img,
news_text: text,
news_url: url
});
});
find_tweets(news_array);
});
}
function find_tweets(news_array) {
for (var i in news_array) {
var news_text = news_array[i].news_text;
$.getJSON("http://search.twitter.com/search.json?q=" + news_text +
"&rpp=10&include_entities=true&result_type=mixed&callback=?",
function (data) {
$.each(data.results, function (i, item) {
var user = item.from_user;
var user_id = item.from_user_id;
var date = item.created_at;
var user_profile_img = item.profile_image_url;
var text = item.text;
var url = (item.entities.urls.length > 0 ? item.entities.urls[0].url : '');
user_tweets.push({
user: user,
user_id: user_id,
date: date,
user_profile_img: user_profile_img,
text: text
});
});
combine_arrays(news_array, user_tweets);
});
}
function combine_arrays(news_array, user_tweets) {
full_array = news_array.concat(user_tweets); console.log(full_array);
}
}
when i use console.log("hello") or try to connect the two arrays everything is executed three times.
You seem to have only one instance of the
news_array
anduser_tweets
arrays. On those, you push all the result of your api queries. Yet, you call thecombine_arrays
function on the whole arrays from a loop (each time after the search gave you a new set of results) - running multiple times over some of the items.I guess re-initializing
inside the
find_tweets
function would help something.You can't access the ajax data outside the callback. Instead, you will need to wait until all the asynchronous requests are resolved. I recommend to use jQuery's Deferred object which makes handling such things much easier:
Usage: