我正在努力解决我经常遇到的一个场景:为 MongoDB 数据库播种。所以我得到了以下脚本,我想将其转换为 Promise,最好使用 ES6,但如果是这种情况,我会采用 bluebird 作为答案。
这是我使用 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!
}
更新了代码以反射(reflect) 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();
});
});
}
});
最佳答案
请尝试通过new Promise
进行操作和 Promise.all
new Promise
创建一个新的 Promise。传入的函数将接收函数resolve和reject作为其参数,可以调用这些函数来密封所创建的promise的命运。
Promise.all
当您想要等待多个 Promise 完成时非常有用。
var bookOps = [];
books.forEach(function (book) {
bookOps.push(saveBookAsync(book));
});
Promise.all(bookOps).then(function() {
bookshelfConn.close(function () {
console.log('Mongoose connection closed!');
});
});
function saveBookAsync(book) {
return new Promise(function(resolve, reject) {
new Book(book).save(function(err) {
if (err)
reject(err);
else
resolve();
})
});
}
关于javascript - 将 Mongoose 播种脚本变成 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35662618/