use*_*506 5 javascript node.js express multer
在下面的代码中,来自 multer API 的目标和文件名选项都是匿名函数。这两个函数都有一个名为cb的参数。这些回调函数是在 multer 模块中定义的还是我应该提供它们?
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)
答案是:是的 cb 由 multer 提供。是的,奇怪的文档对此一无所知。
此回调是所谓的错误优先函数,因此在检查req或文件时,您可能会决定,该用户上传了错误的内容,将new Error()作为第一个参数传递,它将作为响应返回。但请注意,它会在您的应用程序中引发未处理的异常。所以我更喜欢总是传递 null 并在相应的控制器中处理用户输入。
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const error = file.mimetype === 'image/jpeg'
? null
: new Error('wrong file');
cb(error, '/if-no-error-upload-file-to-this-directory');
},
//same for filename
});
Run Code Online (Sandbox Code Playgroud)
注意:我不知道什么是multer
假设你有一个功能,
function destination(req, files){
//something happen here
}
Run Code Online (Sandbox Code Playgroud)
现在在你的代码中你用两个参数调用这个函数
destination(req, files);
Run Code Online (Sandbox Code Playgroud)
而现在如果需要在完成上述函数后立即执行另一个函数,则需要有一个回调函数。假设您需要console.log('Hello world')在目标功能完成后,
destination(req, files , function(){
console.log('hello world')
});
Run Code Online (Sandbox Code Playgroud)
我相信你知道这种功能。现在的问题是目标函数只接受 2 个参数,所以我们需要在函数定义中添加另一个参数。让我们将第三个参数称为“cb”
function destination(req, files, cb){
//something happen here
}
Run Code Online (Sandbox Code Playgroud)
现在cb的类型应该是什么?它应该是一个函数。不是吗?所以如果第三个参数是一个函数,那么我们必须在某个地方执行这个 cb 函数。执行 cb 函数的最佳位置是在目标函数中的所有代码之后。
function destination(req, files, cb){
//something happen here
cb();
}
Run Code Online (Sandbox Code Playgroud)
在这里我们有一个回调函数!!如果你深入思考,你就会明白为什么他们引入了 javaScript Promises
| 归档时间: |
|
| 查看次数: |
3762 次 |
| 最近记录: |