2017-02-03 41 views
0

我正在制作营地应用,用户可以前来创建露营体验和评论。我尝试先删除mongodb中的任何阵营,然后制作3个虚拟阵营数据,然后将它们关联起来。但似乎总是所有3个阵营首先创建,然后评论,因为该评论不能与他们联系在一起。Node.js/Express - 完成第一个功能后,内部回调代码正在运行

Campground.remove({}, function (err) { 
    if (err) { 
     console.log('some error in campground'); 
    } 
    campdata.forEach(function (seed) { 
     Campground.create(seed, function (err, createdData) { 
      if (err) { 
       console.log('camps not created'); 
      } else { 
       // create comments 
       Comment.create({ 
        description: 'this is the best place but wish if there is internet', 
        author: 'satty' 
       }, function (err, commentdata) { 
        if (err) { 
         console.log(err); 
        } else { 
         createdData.comments.push(commentdata); 
         createdData.save(); 
         console.log(commentdata); 
        } 
       }); 
       console.log(createdData); 
      } //else completed 
     }); // campground create completed 
    }); // for each 
    console.log('removed campgrounds'); 
}); // campground remove 

回答

0

请记住,节点是异步的。 forEach同步运行,但其内部的功能是异步的 - 这意味着它们在循环完成后仍在执行。这对你来说是一个问题,因为forEach上的迭代器在执行异步注释添加函数之前已经到达数组中的最后一个元素。解决这个

的一种方式是使用async

(为简洁移除多余代码)

let async = require('async') 

Campground.remove({}, function(err) { 
    async.each(campdata, function(seed, callback) { 
     Campground.create(seed, function(err, createdData) { 
      let comment = { 
       description: 'this is the best place but wish if there is internet', 
       author: 'satty' 
      } 
      Comment.create(comment, function(err, commentdata) { 
       createdData.comments.push(commentdata) 
       createdData.save() 
       callback(err) 
      }) 
     }) 
    }, function(err) { 
     // all done! 
    }) 
}) 
相关问题