multer 中 cb 的空参数是什么?

What is the null argument to cb in multer?

在下面的代码中,来自 multer API,两个 cb 函数将 null 作为它们的第一个参数。 null 的意义是什么?除了 null 之外,这里还可以使用哪些其他值?

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})

var upload = multer({ storage: storage }

采用回调的异步函数通常会格式化回调,以便提供给回调的第一个参数是错误,如果遇到任何错误,而第二个参数是成功检索的值(如果没有遇到错误) .这正是这里发生的事情。如果 destinationfilename 涉及可能引发错误的内容,那么您传递给 cb 的第一个参数可能是错误,例如:

destination: function (req, file, cb) {
  if (!authorized) {
    cb(new Error('You are not authorized to do this!'));
    return;
  }
  cb(null, '/tmp/my-uploads')
}

推理是,如果第一个参数是错误,则通过 cb 的模块会被激励使用和检查第一个参数,从而允许进行适当的错误处理。

例如,如果错误作为 second 参数传递,懒惰的程序员很容易简单地忽略它,并定义回调,使其只查看第一个参数。

这是在其生态系统中开发的 Node.JS 核心和库早期建立的错误优先回调模式。它仍然是一种常见的模式,但主要包含在诸​​如 promises 或 async/await 之类的东西中。这是 Node.JS 文档 https://nodejs.org/api/errors.html#errors_error_first_callbacks.

中的相关部分

null 之外的另一个选项是某种类型 Error 的实例。

null 表示没有错误,您正在调用成功完成的回调和结果值。

node.js 异步回调约定适用于采用两个参数的回调,如果它是已声明的函数,则看起来像这样:

function someCallbackFunction(err, value) {
    if (err) {
        // process err here
    } else {
        // no error, process value here
    }
}

第一个参数是错误(null如果没有错误,如果有错误通常是Error对象的一个​​实例。第二个是一个值(如果没有错误的话)。

因此,如果没有错误,您将 null 作为第一个参数传递,第二个参数将包含您的值。

仅供参考,此回调样式有 node.js documentation