无法理解为什么try和catch在mongoose中没有按预期工作

我是新来的mongoose 。我在我的项目中使用Sails js , Mongo DB和Mongoose 。 我的基本要求是从我的user 集合中查找所有用户的详细信息。 我的代码如下:

 try{ user.find().exec(function(err,userData){ if(err){ //Capture the error in JSON format }else{ // Return users in JSON format } }); } catch(err){ // Error Handling } 

这里user是包含所有user详细信息的模型 。 我有帆解除了我的应用程序,然后我closures了我的MongoDB连接。 我在DHC上运行了API ,发现如下:

  1. 当我一次在DHC上运行这个API的时候, API花费了30多秒的时间来向我显示一个MongoDB 连接不可用的错误
  2. 当我第二次运行这个API的时候, API没有给出响应就超时了。

我的问题在这里为什么trycatch块无法在mongoose有效地处理这样的错误 exception ,或者是我做错了什么?

编辑我的要求是,如果数据库连接不存在,mongoose应立即显示错误。

首先让我们看看使用同步使用模式的函数。

 // Synchronous usage example var result = syncFn({ num: 1 }); // do the next thing 

当函数syncFn被执行时,函数syncFn执行,直到函数返回,你可以自由地做下一件事情。 实际上,同步函数应该被包装在try / catch中。 例如,上面的代码应该是这样写的:

 // Synchronous usage example var result; try { result = syncFn({ num: 1 }); // it worked // do the next thing } catch (e) { // it failed } 

现在我们来看一下asynchronous函数的使用模式。

 // Asynchronous usage example asyncFn({ num: 1 }, function (err, result) { if (err) { // it failed return; } // it worked // do the next thing }); 

当我们执行asyncFn我们传递了两个参数。 第一个参数是函数使用的标准。 第二个参数是一个callback,只要asyncFn调用callback就会执行。 asyncFn将在callback中插入两个参数 – errresult )。 我们可以使用这两个参数来处理错误和做结果的东西。

这里的区别在于,对于asynchronous模式,我们在asynchronous函数的callback中做下一个事情。 真的就是这样。