.each()循环在启动之前等待另一个循环完成

时间:2015-06-09 12:26:50

标签: javascript jquery loops

我有postscomments的两个主循环。但是评论不会显示,大概是因为帖子ID还没有在DOM上(?)。

$.getJSON('fresh_posts.php',function(data){

    //posts 

    $.each(data.freshposts, function(id, post) {
        // set variables and append divs to document
        var id = post.id;
        ...
    });

    // comments attached to each post

    $.each(data.freshcomments, function(id, commentList) {
        $.each(commentList, function(index, c) {
            // set variables and append comments to each post div
            var postid = c.postid; // this is the same as post.id (linked)
            ...

            var full = "<div> ... </div>";

            $('#comment-block'+postid).append(full); // comment-block+postid is attached with each post div, so it tells the comment which div it should be appended to.
        })
    });
});

不显示评论^

如果我在$.each中包含注释的setTimeOut(function(){},1)循环,则可以显示注释 - 我想它需要在循环开始之前等待1毫秒?然而,这似乎不是一种很好的/万无一失的方法来确保这一点。

setTimeOut(function(){
    $.each(data.freshcomments, function(id, commentList) {
        ...
    })
},1)

显示评论^

1 个答案:

答案 0 :(得分:1)

经过几个小时的工作,我设法解决了这个问题。

我创建了两个函数getPosts()appendComments()。我使用了promise方法:

function getPosts(){

    var deferred = new $.Deferred(); // new deferred

    $.getJSON('fresh_posts.php',function(data){
        global_save_json = data.freshcomments;
        var howManyPosts = Object.keys(data.freshposts).length; // how many posts there are (object length)
        var arrayCount = 0;
        $.each(data.freshposts, function(id, post) {

// closing tags for above

return deferred.promise();

}

我有一个异步方法(只是学到了什么)来检查图像是否是为getPosts内的视网膜显示而设计的。

if (retina === "true") {

    var img = new Image();
    img.onload = function() {

        var retina_width = this.width/2;
        var post = '...';
        $('.main').append(post);
        arrayCount++; // for each post add +1 to arrayCount
        if  (arrayCount == howManyPosts) { // if last post
            deferred.resolve();
        }
    }
  img.src = image;

  } else {
  ...

然后我做了

getPosts().then(appendComments);

关闭函数getPosts的标记后

。所以基本上即使函数完成,它仍然等待异步方法在函数getComments被调用之前也在该函数内完成。这样,帖子ID将存在于文档中,以便附加注释。

appendComments看起来像这样:

function appendComments(){

    if (global_save_json != null){
        $.each(global_save_json, function(id, commentList) {
        $.each(commentList, function(index, c) {