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

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

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

谁能告诉我为什么这应该是,也许提供一个解决方法?

一切工作,因为它应该是。

数据库连接是asynchronous的,因此在连接build立之前,“扼杀”你的任务。

你的任务应该是这样的:

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

有关这个咕噜文档中的整个部分: 为什么我的asynchronous任务不完成?