db连接的初始化 - nodejs

时间:2016-02-12 17:53:58

标签: node.js asynchronous gridfs-stream

我想在nodejs应用程序中使用gridfs-stream。

documentation中提供了一个简单的例子:

var mongoose = require('mongoose');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;

mongoose.connect('mongodb://localhost:27017/test');

// make sure the db instance is open before passing into `Grid`
mongoose.connection.once('open', function () {
  var gfs = Grid(mongoose.connection);

  // all set!
})

我的问题由评论描述:

  

确保数据库实例在传入Grid

之前已打开

我尝试在帖子请求中使用gfs。现在,当代码初始化时,gfs变量尚未定义。

api.post('/upload', function(req, res) {
  req.pipe(gfs.createWriteStream({
    filename: 'test'
  }).on('close', function(savedFile){
    console.log('file saved', savedFile);
    return res.json({file: savedFile});
  }));
})

从回调中初始化我的路线似乎有些奇怪。 我在这篇文章(Asynchronous initialization of Node.js module)中读到要求('')是同步执行的,因为我依赖建立的连接,我有点被迫等待

基本上我不确定我现在是否应该在启动时使用异步模式,或者如果我错过了更优雅的方法来解决这个问题。

1 个答案:

答案 0 :(得分:0)

I have a very similar problem with my server. In my case I am reading https certs asynchronously, the software version from git asynchronously and I want to make sure I have it all together by the time the user comes to log in so I can pass the software version back as a reply to login.

The solution is to use promises. Create the promises on user start up for each activity. Then in the code where you want to be sure its all ready, just call then on either the promise itself or Promise.all(array of promises).then()

Here is an example of what I am doing to read the ssl certs to start the server

  class Web  {
    constructor(manager,logger) {
      var self = this;
      this.server = false;
      this.logger = logger;
      var key = new  Promise((resolve,reject) => {
        fs.readFile(path.resolve(__dirname, 'key.pem'),(err,data) => {
          if (err) {
            reject(err);
          } else {
            resolve(data);
          }
        });
      });
      var cert = new Promise((resolve,reject) => {
        fs.readFile(path.resolve(__dirname, 'certificate.pem'), (err,data) => {
          if (err) {
            reject(err);
          } else {
            resolve(data);
          }
        });
      });

      Promise.all([key,cert]).then(values => {
        var certs = {
          key: values[0],
          cert: values[1],
        };
        return certs;
      }).then(certs => {
        self.server = require('http2').createServer(certs,(req,res) => {
        // NOW Started and can do the rest of the stuff
        });
        self.server.listen(...);
      });
 NEEDS SOME MORE CLOSING BRACKETS