You seem to have only one instance of the news_array
and user_tweets
arrays. On those, you push all the result of your api queries. Yet, you call the combine_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
var user_tweets = [];
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:
function news_tweets(query, user_id, count) {
var news_array = [],
user_tweets = [];
return $.getJSON("https://api.twitter.com/1/statuses/user_timeline.json", {
include_entities: "true",
include_rts: "false",
user_i: user_id,
count: count
}).then(function (data) {
return $.when.apply(null, $.map(data, function (item) {
news_array.push({
news_user: item.user.name,
news_date: item.created_at,
news_profile_img: item.user.profile_image_url,
news_text: item.text,
news_url: item.entities.urls.length ? item.entities.urls[0].url : ''
});
return $.getJSON("http://search.twitter.com/search.json", {
q: item.text,
rpp: 10,
include_entities: "true",
result_type: "mixed"
}).done(function (data) {
$.each(data.results, function (i, item) {
user_tweets.push({
user: item.from_user,
user_id: item.from_user_id,
date: item.created_at,
user_profile_img: item.entities.urls.length ? item.entities.urls[0].url : '',
text: item.text
});
});
});
}));
}).then(function() {
// this callback is executed [once] when all requests are done
// and the user_tweets array is filled
// arguments is an array of all search request results
var full_array = news_array.concat(user_tweets);
console.log(full_array);
return full_array;
})
}
Usage:
news_tweets(…).done(function callback(full_array) {
// do something with all the objects
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…