Javascript Node.js-回调在被命中时不会停止执行

Javascript Node.js-回调在被命中时不会停止执行,javascript,node.js,callback,Javascript,Node.js,Callback,我一直在使用node.js开发一个应用程序,在极少数情况下,回调在得到它时不会停止执行,并且执行会继续 方法1 因此,我使用下面的代码方法2来停止执行 方法2 我不知道为什么方法1失败了。哪一种是正确的使用方法? 还有为什么方法1失败了 **注意:我在async.each中使用上述方法。 **方法1的错误在于您的IFER子句中没有return语句,因此回调方法会被调用两次 如果您真的想停止程序的执行,您应该在这里做的是抛出一个异常 Model.find().exec(function(err,r

我一直在使用node.js开发一个应用程序,在极少数情况下,回调在得到它时不会停止执行,并且执行会继续

方法1

因此,我使用下面的代码方法2来停止执行

方法2

我不知道为什么方法1失败了。哪一种是正确的使用方法? 还有为什么方法1失败了

**注意:我在async.each中使用上述方法。
**

方法1的错误在于您的IFER子句中没有return语句,因此回调方法会被调用两次

如果您真的想停止程序的执行,您应该在这里做的是抛出一个异常

Model.find().exec(function(err,result) {
  if(err) {
    throw new Error(err);
  }

  // .. do what you want with the result ..
});

要退出函数,需要使用return。从:

在函数中调用return语句时,此函数的执行将停止。如果指定,将向函数调用方返回给定值。如果省略表达式,则返回undefined

因此,Model2是正确的方法,尽管可以稍微清理一下:

Model.find().exec(function(err, result) {
  if (err) { return callback(err); } // will exit here if error

  // no need to explicitly return here as it's the termination of the function
  callback(null, result); // result could be null but callback can handle that
});
除非您在该函数中执行某些操作,否则您可以通过使用以下命令将此逻辑推入回调:

Model.find(callback);

function callback(err, result) {
  if (err) {
    // do something with err
  }

  // do soemthing with result
  // ....
}

Sry。刚刚更新了实际的实现。谢谢你的意见。我已经决定使用return,但我想确保我没有在任何地方出错,这是唯一的错误。但你应该尝试使用例外或承诺,这样会更干净:!我以为OP想要退出函数而不是程序?如果捕捉正确,抛出异常不一定会停止应用程序!如果捕获正确,则表示同意,但这是节点回调模式的要点。根据需要冒泡出错误,而不必将函数埋在一堆try/catch块中。
Model.find().exec(function(err, result) {
  if (err) { return callback(err); } // will exit here if error

  // no need to explicitly return here as it's the termination of the function
  callback(null, result); // result could be null but callback can handle that
});
Model.find(callback);

function callback(err, result) {
  if (err) {
    // do something with err
  }

  // do soemthing with result
  // ....
}