[英]Why don't these JavaScript loops work as expected?
我正在尝试为我的 mongoose 数据库创建一个播种器函数,到目前为止我编写的代码实际上有效,我只是无法理解执行操作的顺序。 这是源代码:
var mongoose = require('mongoose'),
Book = require('./models/book'),
Chapter = require('./models/chapter');
var books = [
{
title: '12 Rules For Life',
author: 'Jordan B. Peterson',
cover: '',
ISBN: 1241232,
description: 'A self-help book written by Canadian psychologist Jordan B. Peterson',
status: 'reading'
},
{
title: "Charllote's Web",
author: 'EB White',
cover: '',
ISBN: 1243575,
description: 'The story of a girl who raises a pig and a spider',
status: 'read'
},
{
title: 'A Fraction Of The Whole',
author: 'Steve Toltz',
cover: '',
ISBN: 1241686,
description: 'A book telling the story of three generations of the Toltz family',
status: 'want to read'
}
];
var chapters = [
{
title: 'First Chapter - How It All Began',
body: 'This is how it all began'
}
];
function seedDb() {
// delete all books and chapters
Book.deleteMany({}, function(err) {
if (err) {
console.log(err);
} else {
console.log('Removed all books');
Chapter.deleteMany({}, function(err) {
if (err) {
console.log(err);
} else {
console.log('Removed all chapters');
// add new books to the database from books array
books.forEach(function(book) {
Book.create(book, function(err, createdBook) {
if (err) {
console.log(err);
} else {
console.log('Created The Book ' + createdBook.title);
// add new chapters to the book created
for (var i = 0; i < chapters.length; i++) {
Chapter.create(chapters[i], function(err, createdComment) {
if (err) {
console.log(err);
} else {
console.log('Created chapter for ' + createdBook.title);
createdBook.chapters.push(createdComment);
}
createdBook.save(function(err) {
if (err) {
console.log(err);
} else {
console.log('Associated Chapter with the book ' + createdBook.title);
}
});
});
}
}
});
});
}
});
}
});
}
module.exports = seedDb;
这是操作发生的顺序:在此处输入图像描述
订单不应该是这样的:
async function seedDb(){
try{
await Book.deleteMany({});
await Chapter.deleteMany({});
for(let book of books){
const createdBook = await Book.create(book);
for(let chapter of chapters){
if(createdBook.chapters) createdBook.chapters.push(chapter);
else createdBook.chapters = [chapter];
await createdBook.save();
}
}
}catch(err){
console.log(err);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.