为什么这个MongoDB连接不能在grunt脚本中工作?

时间:2013-11-11 17:40:33

标签: node.js mongodb gruntjs

如果我使用节点运行它,则打印“已连接到数据库”:

var MongoClient = require("mongodb").MongoClient;
MongoClient.connect("mongodb://localhost/db1", function(err, db) {
  if (err) {
    throw err;
  }
  console.log("Connected to Database");
  db.close();
});

但是,如果我尝试使用Grunt任务运行它,它什么都不做,而且是静默的。

module.exports = function(grunt) {
  return grunt.registerTask("task", "subtask", function() {
    var MongoClient = require("mongodb").MongoClient;
    return MongoClient.connect("mongodb://localhost/db1", function(err, db) {
      if (err) {
        throw err;
      }
      console.log("Connected to Database");
      db.close();
    });
  });
};

任何人都可以告诉我为什么这应该是并且可能提供一种解决方法吗?

1 个答案:

答案 0 :(得分:2)

一切都按原样运作。

数据库连接是异步的,因此在建立连接之前,grunt会“终止”你的任务。

你的任务应该是这样的:

module.exports = function(grunt) {
  return grunt.registerTask("task", "subtask", function() {
    var done = this.async();
    var MongoClient = require("mongodb").MongoClient;
    MongoClient.connect("mongodb://localhost/db1", function(err, db) {
      if (err) {
        done(false);
      }
      console.log("Connected to Database");
      db.close();
      done();
    });
  });
};

grunt文档中有关于此的整个部分:Why doesn't my asynchronous task complete?