0

I have the following code

for (var i = 1; i<=10;  i++){
temp = "resp.items[" + (i-1).toString() + "].snippet.thumbnails.medium.url";
thumbnail = '<img src="' + eval(temp) + '">';

$("#yt_" + i.toString()).append("<a href='#'>" + thumbnail + "<br>" + resp.items[i-1].snippet.title + "</a>");

if(typeof (resp.items[i-1].contentDetails.upload) != 'undefined')
    ytid = resp.items[i-1].contentDetails.upload.videoId;
else if(typeof (resp.items[i-1].contentDetails.recommendation) != 'undefined')
    ytid = resp.items[i-1].contentDetails.recommendation.resourceId.videoId;
else
    ytid = resp.items[i-1].contentDetails.playlistItem.resourceId.videoId;

newurl = "https://gdata.youtube.com/feeds/api/videos/" + ytid +"?v=2&alt=jsonc&callback=?";

console.log("i is " + i);

    //The following is executed after the loop finishes
$.getJSON(newurl, function (dur) {
     duration_reco = dur.data.duration;
     data[i-1] = {
                       "logo" : "logos/youtube_vsmall.png", 
                       "video_low" : "",
                       "thumb" : resp.items[i-1].snippet.thumbnails.medium.url, 
                       "title" : resp.items[i-1].snippet.title.substring(0,15) + '...' + secondsToHms(duration_reco), 
                       "author" : "koustubh", 
                       "tags" : ["1","2","3"],
                       "themes" : ["1","2","3"],
                       "link" : "playVideo?vid=" + ytid + "&service=youtube"
                     };
     });
} 

I just found out that the $.getJSON function executes after completing the entire for loop. What can I do to make it wait and execute and follow the code order.

chridam
  • 100,957
  • 23
  • 236
  • 235
user3392740
  • 445
  • 2
  • 7
  • 19
  • 1
    possible duplicate of [Is there a version of $getJSON that doesn't use a call back?](http://stackoverflow.com/questions/933713/is-there-a-version-of-getjson-that-doesnt-use-a-call-back) – Patrick Evans Mar 08 '14 at 03:29

1 Answers1

1

You should use $.ajax({...}) so you can add {async:false} in parameters Like

$.ajax({
   url : "xyz.php", 
   async : false,
   dataType : json
   success : function(data){
           //code here
   }
});

You can also add {async:false} globally.

NOTE: This will work with all ajax function that define on page

$.ajaxSetup({async:false});
Girish
  • 11,907
  • 3
  • 34
  • 51
  • I tried to use it, but it doesnt work. It seems that the use of async:false is deprecated for jquery 1.8+ . Is there a workaraound or something else that I can try – user3392740 Mar 08 '14 at 05:58