我正在寻找同时运行多个不同的JSON请求,然后只在完成或返回错误消息(404等)后才执行函数。以下是我目前为止的内容,但函数finished
不记得来自任何请求的变量。有任何想法吗?等待多个异步JSON查询在运行代码之前完成
function socialPosting(a_date,a_title,a_source,a_thumbnail,a_url) {
socialPosts[socialPosts.length] = {date: a_date, title: a_title, source: a_source, thumbnail: a_thumbnail, url: a_url};
//console.log(socialPosts[amount]);
//console.log(amount);
}
function finished(source) {
if (source == "Twitter") {
var Twitter = "True";
}
if (source == "YouTube") {
var YouTube = "True";
}
console.log(source); //diagnostics
console.log(Twitter); //diagnostics
console.log(YouTube); //diagnostics
if (Twitter == "True" && YouTube == "True") {
console.log(socialPosts[0]); //Should return after both requests are complete
}
}
$.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-results=5&v=2&alt=jsonc&orderby=published', function(data) {
for(var i=0; i<data.data.items.length; i++) { //for each YouTube video in the request
socialPosting(Date.parse(data.data.items[i].uploaded),data.data.items[i].title,"YouTube",data.data.items[i].thumbnail.hqDefault,'http://www.youtube.com/watch?v=' + data.data.items[i].id); //Add values of YouTube video to array
}
finished("YouTube");
});
$.getJSON("https://api.twitter.com/1/statuses/user_timeline/twitter.json?count=5&include_rts=1&callback=?", function(data) {
var amount = socialPosts.length;
for(var i=0; i<data.length; i++) {
socialPosting(Date.parse(data[i].created_at),data[i].text,"Twitter"); //Add values of YouTube video to array
}
finished("Twitter");
});
这就是承诺是添加错误处理程序到你的JSON请求。 – SLaks
我不同意它是重复的,因为这里的解决方案与我在问题中所做的更接近重复。 – Sam
当然,但*总体问题*是相同的。 –