我正试图绕过承诺试图解决我发现自己很多次的场景:播种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();
});
});
}
});
答案 0 :(得分:1)
请尝试通过new Promise
和Promise.all
new Promise
创建一个新的承诺。传入函数将接收函数resolve和reject作为其参数,可以调用它来密封创建的promise的命运。
Promise.all
对于您希望等待多个承诺完成时非常有用。
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();
})
});
}