Node.js NodeJS-未调用箭头函数?

Node.js NodeJS-未调用箭头函数?,node.js,anonymous-function,arrow-functions,Node.js,Anonymous Function,Arrow Functions,我尝试将一个arrow函数拆分为两个,以便尝试将一些外部变量传递到两个函数之间的内部变量(范围方面) 这是原始功能: app.post('/single', upload.single('image'), (req, res, next) => { res.status(200).send('File uploaded successfully.') }); 这是新的,分裂的一个: app.post('/single', (req, res, next) => {

我尝试将一个arrow函数拆分为两个,以便尝试将一些外部变量传递到两个函数之间的内部变量(范围方面)

这是原始功能:

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')从未被调用,图片上传过程也没有被调用?(尽管它只是嵌套的)。
是什么原因造成的

多谢各位

问题是,在第二个示例中,console.log('2')从未被调用,图片上传过程也没有被调用?(尽管它只是嵌套的)。 是什么原因造成的

upload.single('image')
是中间件。这意味着,当您调用它时,它只返回另一个函数,该函数期望作为参数传递
req
res
next

那么,你在做什么:

upload.single('image', () => {... });
只会返回一个从未调用过的函数,也不会调用传递的回调函数,因为这不是
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
是否有错误,只有在没有错误时才继续。

不完全确定,但可能是
。single
只接受一个参数?如果你再传一次,它可能就被忽略了