【问题标题】:Turning a Mongoose seeding script into a promise将 Mongoose 播种脚本变成承诺
【发布时间】: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


    【解决方案1】:

    请尝试通过new PromisePromise.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();
            })
        });
    }
    

    【讨论】:

    • 感谢它完美运行。我根本不知道Promise.all ))
    猜你喜欢
    • 2015-02-25
    • 2017-02-15
    • 1970-01-01
    • 2015-01-21
    • 2017-10-13
    • 2019-10-21
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    相关资源
    最近更新 更多