javascript - Node 中的异步方法没有收到错误

标签 javascript node.js

我使用以下代码

require('./ut/valid').validateFile()

});

在验证文件中,当我发现配置中有一些重复项时,我发送错误 就像下面的

module.exports = {
    validateFile: function (req) {
...
if(dup){
console.log("Duplicate found: ");
return new Error("Duplicate found: ");
}

dup 为 true 并且应该抛出错误,我应该如何在异步方法中“捕获”它?

我也尝试过如下

require('./ut/valid').validateFile(function() {
    process.exit(1);
});

我在这里想念的是,我能够看到控制台日志......

最佳答案

您的方法不起作用,因为您正在执行异步操作。常见的解决方案是使用回调。在 Node.js 中,通常使用名为 error first callbacks 的模式。 .

这意味着您需要将回调函数传递给您的文件验证方法,并返回错误或您的文件:

  // './utils/validate.js'
  module.exports = {

    /**
     * Validates a file.
     *
     * @param {Function} next - callback function that either exposes an error or the file in question
     */
    file: function (next) {
      // ...

      if (duplicate) {
        console.log('Duplicate found!');

        var error = new Error('Duplicate File');
        // Perhaps enrich the error Object.

        return next(error);
      }

      // Eveything is ok, return the file.
      next(null, file);
    }
};

你可以像这样使用它:

 // './app.js'
var validate = require('./utils/validate');

validate.file(function (err, file) {
  if (err) {
    // Handle error.
    process.exit(1);
  }

  // Everything is ok, use the file.
  console.log('file: ', file);
});

关于javascript - Node 中的异步方法没有收到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31724203/

相关文章:

javascript - Highcharts.js 中多轴的工具提示格式化程序

node.js - 在 NodeJS/Express 的 POST 方法中从 URL 获取参数

Javascript 函数 Hook

javascript - 在 Node.js 中,如何存储主应用程序中模块函数的回调数据?

ios - 亚马逊S3下载: Direct iOS or Web Service Node Js.?

node.js - fs.readFile 在 Docker 容器中的行为不同

node.js - 带有 Node.js 的谷歌云消息传递 XMPP 服务器

mysql - 使用NodeJS和MySQL无法通过id获取数据

javascript - 如何访问Polymer元素模板内js文件中定义的函数?

javascript - 在 Javascript "N�O�T�I�C�E�"中显示文本时出现问题,php 显示它没有问题