NodeJS - 箭头函数没有被调用?
NodeJS - Arrow function not being called?
我尝试将箭头函数拆分为两个,以便尝试将一些外部变量传递到两者之间的内部变量(就范围而言)。
这是原始函数:
app.post('/single', upload.single('image'), (req, res, next) => {
res.status(200).send('File uploaded successfully.')
});
这是新的拆分版:
app.post('/single', (req, res, next) => {
upload.single('image', () => {
console.log('2');
res.status(200).send('File uploaded successfully.')
}),
});
问题是,在第二个例子中,console.log('2') 从来没有被调用过,图片上传过程也没有? (虽然它只是嵌套)。
可能是什么原因造成的?
谢谢。
The problem is, on the second example, console.log('2') is never being called, and the picture upload process isn't too? (although it is only nested).
What may cause that?
upload.single('image')
是中间件。这意味着当您调用它时,它只是 return 另一个函数,并且该函数期望作为参数传递 req
、res
和 next
。
所以,你在做什么:
upload.single('image', () => {... });
只会 return 一个永远不会被调用的函数,它永远不会调用传递的回调,因为这不是 upload.single()
设计的工作方式。
如果你真的想手动调用它(我不推荐),你必须这样做:
app.post('/single', (req, res, next) => {
upload.single('image')(req, res, (err) => {
if (err) {
return next(err);
}
console.log('2');
res.status(200).send('File uploaded successfully.')
}),
});
您调用 upload.single()
获取中间件函数,然后调用该函数并将其传递给所需的 (req, res, next)
,但您用自己的回调替换了 next
参数,并且然后在该回调中,您检查中间件的 next
是否被错误调用,只有在没有错误时才继续。
我尝试将箭头函数拆分为两个,以便尝试将一些外部变量传递到两者之间的内部变量(就范围而言)。
这是原始函数:
app.post('/single', upload.single('image'), (req, res, next) => {
res.status(200).send('File uploaded successfully.')
});
这是新的拆分版:
app.post('/single', (req, res, next) => {
upload.single('image', () => {
console.log('2');
res.status(200).send('File uploaded successfully.')
}),
});
问题是,在第二个例子中,console.log('2') 从来没有被调用过,图片上传过程也没有? (虽然它只是嵌套)。
可能是什么原因造成的?
谢谢。
The problem is, on the second example, console.log('2') is never being called, and the picture upload process isn't too? (although it is only nested). What may cause that?
upload.single('image')
是中间件。这意味着当您调用它时,它只是 return 另一个函数,并且该函数期望作为参数传递 req
、res
和 next
。
所以,你在做什么:
upload.single('image', () => {... });
只会 return 一个永远不会被调用的函数,它永远不会调用传递的回调,因为这不是 upload.single()
设计的工作方式。
如果你真的想手动调用它(我不推荐),你必须这样做:
app.post('/single', (req, res, next) => {
upload.single('image')(req, res, (err) => {
if (err) {
return next(err);
}
console.log('2');
res.status(200).send('File uploaded successfully.')
}),
});
您调用 upload.single()
获取中间件函数,然后调用该函数并将其传递给所需的 (req, res, next)
,但您用自己的回调替换了 next
参数,并且然后在该回调中,您检查中间件的 next
是否被错误调用,只有在没有错误时才继续。