2013-06-05 4 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

이 시도, 솔루션에 트위터와 유튜브는 함수의 지역 변수는 함수가 다시 호출되는 경우, 그들은 더 이상 존재하지 않는 함수가 반환 한 후, 그들은 다시 craeted되어 완료하지만 물론 그들은하지는 그들은 새로운 변수이기 때문에 지난 시간의 가치를 가지고 있습니다. 아마도이 주제에 대한 더 자세한 정보는 'javascript variable scope'에 대한 google을 참조하십시오.

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

그게 왜 효과가 내 마음을 boggles. 나중에 추가 할 예정 이었지만 사실인지 확인하는 경우 정의되지 않은 것과 true 사이에 차이가 있음을 알지 못했습니다. Thankyou – Sam

+0

키 변경은 함수에서 변수 선언을 이동하지 않고 함수에서 제외시키는 것입니다. string에서 booleans로 값을 변경하는 것은 필요하지 않았지만 그 코드를 볼 수는 없었습니다.) – luk2302

+0

그래, 원래는 (부울이라고 생각한 것)하지만 오류가있었습니다. . 나는 진실 대신에 참을 사용했다. – Sam

관련 문제