2013-06-05 46 views
0

我正在寻找同时运行多个不同的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"); 
    }); 
+2

这就是承诺是添加错误处理程序到你的JSON请求。 – SLaks

+0

我不同意它是重复的,因为这里的解决方案与我在问题中所做的更接近重复。 – Sam

+0

当然,但*总体问题*是相同的。 –

回答

1

试试这个,在您的解决方案Twitter和YouTube在函数的局部变量完成后,该函数返回他们不再存在后,如果函数被再次调用它们再次craeted但当然他们鸵鸟政策具有上次的价值,因为它们是新的变量,可能是谷歌的'JavaScript变量范围'关于此主题的更多信息。

var Twitter = false; 
var YouTube = false; 
function finished(source) { 
    if (source == "Twitter") { 
     Twitter = true; 
    } 
    if (source == "YouTube") { 
     YouTube = true; 
    } 
    console.log(source); 
    console.log(Twitter); 
    console.log(YouTube); 
    if (Twitter && YouTube) { 
     console.log(socialPosts[0]); 
    } 
} 

而且通过
$.getJSON(...).fail(function() {console.log('error');});

+0

它令我难以置信的原因为何如此。我后来补充说,但是在检查它们是否属实时,并没有意识到未定义和真实之间有什么区别。 Thankyou – Sam

+0

关键的变化是将变量声明移出函数,而不是将函数放在函数中。 从字符串改变他们的价值wasn't必要为这个布尔值,但我couldn't看的代码,它在;) – luk2302

+0

是啊,我本来有它(我认为是布尔值),但它给了我错误。原来我是用True而不是真的。 – Sam

相关问题