将猫鼬播种脚本变成承诺 [英] Turning a Mongoose seeding script into a promise

查看:51
本文介绍了将猫鼬播种脚本变成承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图绕过诺言,试图解决很多情况下发现的自己的问题:播种MongoDB数据库.因此,我得到了以下脚本,我希望将其转换为Promise,最好使用ES6,但如果是这样的话,它将以蓝鸟作为答案. 这是我在关闭数据库之前使用setTimeout给予时间写操作的时间:

I'm trying to wrap my head around promises trying to solve a scenario I find myself in a lot of times: seeding a MongoDB database. So I got the following script which I want to turn into a Promise, preferably using ES6, but would take a bluebird as an answer if that's the case. This is what I got using setTimeout to give time to the write operations before closing the database:

// 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的答案:

Updated code to reflect zangw's answer:

// 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();
      });
    });
  }
});

推荐答案

请尝试通过 Promise.all

Please try to do it through new Promise and Promise.all

new Promise创建新的诺言.传入的函数将接收函数resolve和reject作为其参数,可以调用这些函数来密封所创建的Promise的命运.

new Promise to create a new promise. The passed in function will receive functions resolve and reject as its arguments which can be called to seal the fate of the created promise.

Promise.all在您要等待一个以上的诺言完成时很有用.

Promise.all is useful for when you want to wait for more than one promise to complete.

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();
        })
    });
}

这篇关于将猫鼬播种脚本变成承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆