代码如下,data
是长度为3的一个数组,cmt
是个object
function addComments(campground, cmt) {
Comment.create(
cmt,
function(err, comment) {
if (err) console.log(err);
else {
campground.comments.push(comment);
campground.save();
console.log("Created new comment");
}
});
}
function addCamps(seed) {
Camp.create(seed, function(err, campground){
if (err) console.log(err);
else {
console.log("Added a campground");
addComments(campground, cmt);
}
});
}
function seedDB(){
Camp.remove({}, function(err) {
if (err) console.log(err);
else {
console.log("removed campgrounds");
Comment.remove({}, function(err) {
if (err) console.log(err);
else {
console.log("removed comments");
data.forEach(addCamps);
}
});
}
});
}
seedDB();
请问为什么输出结果是
removed campgrounds
removed comments
Added a campground
Added a campground
Added a campground
Created new comment
Created new comment
Created new comment
而不是
removed campgrounds
removed comments
Added a campground
Created new comment
Added a campground
Created new comment
Added a campground
Created new comment
如果想让结果变成第二种情况,应该如何修改以上代码?
应该如何修改以上代码?
因为回调函数的特点就是无需等待,且回调执行的时间也不确定。你这里出现这种输出顺序的原因是执行
addComments
时花了些时间。如果你想要按
Added a campground、Created new comment
这样交替打印的话,就需要等待前一个comment
完成再执行下一个capmgroup
的添加了。这就放弃了js异步的优势。现在data数据只有三个不算多,但是数据一多就会影响体验,用户会看到最后面的comment添加的比第一个迟的多。代码的话可以用
Promise
:同时不能再使用
forEach
而是使用for
循环: