use*_*506 2 javascript node.js express 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 }
Run Code Online (Sandbox Code Playgroud)
采用回调的异步函数通常会格式化回调,以便提供给回调的第一个参数是错误(如果遇到任何错误),而第二个参数是成功检索到的值(如果没有遇到错误)。这正是这里发生的事情。如果destination
或filename
涉及可能引发错误的内容,那么您传递给的第一个参数cb
可能是错误,例如:
destination: function (req, file, cb) {
if (!authorized) {
cb(new Error('You are not authorized to do this!'));
return;
}
cb(null, '/tmp/my-uploads')
}
Run Code Online (Sandbox Code Playgroud)
推理是,如果第一个参数是错误,则通过的模块cb
会被激励使用和检查第一个参数,从而允许正确的错误处理。
例如,如果错误作为第二个参数传递,那么懒惰的程序员很容易忽略它,并定义回调以使其仅查看第一个参数。
归档时间: |
|
查看次数: |
2183 次 |
最近记录: |