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

Unable to understand why the try and catch is not working as expected in mongoose

我是项目中 mongoose.I am using Sails js, Mongo DB and Mongoose 的新手。我的基本要求是从我的 user collection 中找到所有用户的详细信息。我的代码如下:

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 详细信息。我让帆升起我的应用程序,然后我关闭了我的 MongoDB 连接。我 运行 APIDHC 上发现了以下内容:

  1. 当我 运行 APIDHC 第一次 时,API 花了超过 30 秒向我展示一个 error MongoDB connection 不可用。
  2. 当我运行API的时候,API超时没有回应

我的问题是为什么 trycatch 块无法处理这样的 error exceptionmongoose 中有效,还是我做错了什么?

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

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

// Synchronous usage example

var result = syncFn({ num: 1 });

// do the next thing

当函数syncFn执行时函数依次执行直到函数 returns 然后你就可以自由地做下一件事了。实际上,同步函数应该是 包裹在 try/catch 中。比如上面的代码应该这样写:

// Synchronous usage example

var result;

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

现在让我们看一下异步函数的使用模式。

// Asynchronous usage example

asyncFn({ num: 1 }, function (err, result) {
  if (err) {
    // it failed
    return;
  }

  // it worked
  // do the next thing
});

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

这里的区别在于,对于异步模式,我们在异步函数的回调中执行下一件事。真的就是这样。