同步执行

时间:2014-03-08 03:21:37

标签: javascript synchronous

我有以下代码

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"
                     };
     });
} 

我刚刚发现$.getJSON函数在完成整个for循环后执行。我该怎么做才能让它等待并执行并遵循代码顺序。

1 个答案:

答案 0 :(得分:1)

您应该使用$.ajax({...}),以便在参数中添加{async:false} 喜欢

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

您还可以全局添加{async:false}

注意:这适用于在页面

上定义的所有ajax函数
$.ajaxSetup({async:false});