0

我在 $.each 循环中调用了一个函数,但我想确保在前一个函数完成之前不会调用下一次迭代。

$(".btn_loadfavorites").on("click",function(event){
 $.getJSON('utility/get_user_compare_pages.php', {uid: user}, function(rsp) {
  $.each(rsp, function(i, favorite_pageid) {
   loadNewFacebookPage(favorite_pageid);
  });
 });  
});

这是函数(我去掉了不重要的东西):

function loadNewFacebookPage(newfbpage){

  if (isUrl(newfbpage) || newfbpage.substr(0,3) == "www"){
    newfbpage = newfbpage.substr(newfbpage.lastIndexOf('/') + 1);
  }

  $.getJSON( "https://graph.facebook.com/"+newfbpage+"?fields=picture,name,category,likes,talking_about_count,link,website" )
  .done(function( rsp ) {
      $('#loadmodal').modal('show');
      var newpageid = rsp.id;
      $("*[data-pcpageid]").each(function(i, elm) {
        if(newpageid == $(this).data("pcpageid")){
          pageexists = true;
          alert('Page has already been added');
          return;
        }
      });
      if(pageexists == false){
        pagename = rsp.name.split(" ");
        pagepicture = rsp.picture.data.url;
        $('.grid_fbpages').append("<li class='grid_li_fbpages' data-pcpageid='"+newpageid+"' style='max-width:20%;'><img src='"+pagepicture+"' class='img-circle' style='display:inline;margin-right:15px;'><h4 style='display:inline;'>"+pagename[0]+"</h4><a href='javascript:void(0)' class='btn_removefbpage' style='float:right' data-pcpageid='"+newpageid+"'>&#10005</a> <a href='javascript:void(0)' class='btn_addtofavorites' style='float:right' data-pcpageid='"+newpageid+"'>&#9733;</a><hr>Likes: "+rsp.likes+"<br>PTAT: "+rsp.talking_about_count+"<br><br></li>");
        //GET POSTS
        $.getJSON('utility/get_compare_posts.php', {access_token: access_token, pid: newpageid}, function(rsp) {
          $.each(rsp, function(postId, data) {

            //TOP POSTS
            if (data.hasOwnProperty('likes')){
              top_posts_likes.push(data.likes.like_count);
              if (data.hasOwnProperty('comments')){
                top_posts_comments.push(data.comments.comment_count);
              }else{
                top_posts_comments.push('0');
              }
              top_posts_message.push(data.message);
              top_posts_id.push(data.postId);
            }
          });

          //TOP POSTS
          $(".grid_topposts").append("<li data-pcpageid='"+newpageid+"' style='max-width:20%;text-align:left;'><img src='"+pagepicture+"' class='img-circle' style='display:inline;margin-right:15px;'><h4 style='display:inline;'>"+pagename[0]+"</h4></li>");
          most_popular_post_index = top_posts_likes.indexOf(Math.max.apply(Math, top_posts_likes));
          $.getJSON( "https://graph.facebook.com/"+top_posts_id[most_popular_post_index]+"?fields=picture&access_token="+access_token+"", function(rsp) {
            $(".grid_topposts").append("<li data-pcpageid='"+newpageid+"' style='max-width:20%;'><img src='"+rsp.picture+"'><br>"+top_posts_message[most_popular_post_index]+"<br>Likes: "+top_posts_likes[most_popular_post_index]+" Comments: "+top_posts_comments[most_popular_post_index]+"</li>");
              top_posts_likes.splice(most_popular_post_index,1);
              top_posts_message.splice(most_popular_post_index,1);
              top_posts_id.splice(most_popular_post_index,1);
              top_posts_comments.splice(most_popular_post_index,1);

              most_popular_post_index = top_posts_likes.indexOf(Math.max.apply(Math, top_posts_likes));
              $.getJSON( "https://graph.facebook.com/"+top_posts_id[most_popular_post_index]+"?fields=picture&access_token="+access_token+"", function(rsp) {
                $(".grid_topposts").append("<li data-pcpageid='"+newpageid+"' style='max-width:20%;'><img src='"+rsp.picture+"'><br>"+top_posts_message[most_popular_post_index]+"<br>Likes: "+top_posts_likes[most_popular_post_index]+" Comments: "+top_posts_comments[most_popular_post_index]+"</li>");
                  top_posts_likes.splice(most_popular_post_index,1);
                  top_posts_message.splice(most_popular_post_index,1);
                  top_posts_id.splice(most_popular_post_index,1);
                  top_posts_comments.splice(most_popular_post_index,1);

                  most_popular_post_index = top_posts_likes.indexOf(Math.max.apply(Math, top_posts_likes));
                  $.getJSON( "https://graph.facebook.com/"+top_posts_id[most_popular_post_index]+"?fields=picture&access_token="+access_token+"", function(rsp) {
                    $(".grid_topposts").append("<li data-pcpageid='"+newpageid+"' style='max-width:20%;'><img src='"+rsp.picture+"'><br>"+top_posts_message[most_popular_post_index]+"<br>Likes: "+top_posts_likes[most_popular_post_index]+" Comments: "+top_posts_comments[most_popular_post_index]+"</li>");
                      top_posts_likes.splice(most_popular_post_index,1);
                      top_posts_message.splice(most_popular_post_index,1);
                      top_posts_id.splice(most_popular_post_index,1);
                      top_posts_comments.splice(most_popular_post_index,1);
                  });
              });
          });
          //END TOP POSTS  

        });
      }
  })
  .fail(function( error ) {
    alert('Did not find any match - Please try again with another name, ID or URL');

  });
}

谢谢

4

1 回答 1

1

$.each()是同步的。它只是一个直接调用函数的循环,没有什么花哨或神秘的地方。在您的代码中,$.each()将调用loadNewFacebookPage(),该函数将运行到完成,然后$.each()将移动到下一个元素。

但这真的是你要问的吗?loadNewFacebookPage()听起来它可能是一个异步函数。如果是,您是说要等到异步活动完成后再进行下一个循环迭代?$.each()循环不会那样做。普通的for循环也不会。相反,loadNewFacebookPage()需要提供一个完成回调,并且该回调将推进一个“循环”变量。

如果您能提供更多信息loadNewFacebookPage()——特别是它是否具有完成回调或是否可以添加——那么将更清楚该做什么。

例如,假设loadNewFacebookPage()接受第二个参数,它是一个完成回调函数。然后你可以写这样的代码:

$.getJSON( url, { uid: user }, function( rsp ) {
    var i = 0;
    next();
    function next() {
        if( i < rsp.length ) {
            var favorite_pageid = rsp[i++];
            loadNewFacebookPage( favorite_pageid, next );
        }
    }
});

假设loadNewFacebookPage()正在使用该$.ajax()函数加载数据。(它可能没有这样做,是吗?但这将起到说明作用。)然后你可能会做类似的事情:

function loadNewFacebookPage( id, done ) {
    $.ajax({
        url: makeUrlFromId( id ),
        success: function( data ) {
            doStuffWithData( data );
            done();
        }
    });
}

我在这里省略了一堆东西,比如错误处理,只是为了举例说明。

于 2013-09-06T08:25:11.437 回答