【发布时间】:2016-02-27 16:44:45
【问题描述】:
我正试图围绕承诺试图解决一个我经常发现自己的场景:播种 MongoDB 数据库。所以我得到了下面的脚本,我想把它变成一个 Promise,最好使用 ES6,但如果是这样的话,我会用蓝鸟作为答案。
这就是我在关闭数据库之前使用setTimeout 给写操作留出时间的结果:
// Importing the connection to the `bookshelf` db.
var bookshelfConn = require('./database');
// Importing the Mongoose model we'll use to write to the db.
var Book = require('./models/Book');
// Importing the Data to populate the db.
var books = require('./dataset');
// When the connection is ready, do the music!
bookshelfConn.on('open', function () {
dropDb(seedDb, closeDb);
});
function dropDb (cb1, cb2) {
bookshelfConn.db.dropDatabase();
console.log('Database dropped!');
cb1(cb2);
}
function seedDb (cb) {
console.time('Seeding Time'); // Benchmarking the seed process.
// Warning! Slow IO operation.
books.forEach(function (book) {
new Book(book).save(function (err) {
if (err) console.log('Oopsie!', err);
});
console.log('Seeding:', book);
});
console.timeEnd('Seeding Time'); // Benchmarking the seed process.
cb();
}
function closeDb () {
setTimeout(function () {
bookshelfConn.close(function () {
console.log('Mongoose connection closed!');
});
}, 1000); // Delay closing connection to give enough time to seed!
}
更新代码以反映 zangw 的回答:
// Importing the connection to the `bookshelf` db.
var bookshelfConn = require('./database');
// Importing the Mongoose model we'll use to write to the db.
var Book = require('./models/Book');
// Importing the Data to populate the db.
var books = require('./dataset');
// When the connection is ready, do the music!
bookshelfConn.on('open', function () {
// Here we'll keep an array of Promises
var booksOps = [];
// We drop the db as soon the connection is open
bookshelfConn.db.dropDatabase(function () {
console.log('Database dropped');
});
// Creating a Promise for each save operation
books.forEach(function (book) {
booksOps.push(saveBookAsync(book));
});
// Running all the promises sequentially, and THEN
// closing the database.
Promise.all(booksOps).then(function () {
bookshelfConn.close(function () {
console.log('Mongoose connection closed!');
});
});
// This function returns a Promise.
function saveBookAsync (book) {
return new Promise(function (resolve, reject) {
new Book(book).save(function (err) {
if (err) reject(err);
else resolve();
});
});
}
});
【问题讨论】:
标签: javascript mongodb mongoose