我像这样声明我的函数:
const parseConnections = (connectionsCSVPath, req, res) => {
//do a bunch of stuff
}
在函数内部,如果我尝试调用 res.locals.something,我会收到一个错误,说"无法读取未定义的属性局部变量"我尝试了其他几种语法,例如:
const parseConnections = ((connectionsCSVPath, req, res) => {
//do a bunch of stuff
})
这:
const parseConnections = (connectionsCSVPath, (req, res) => {
//do a bunch of stuff
})
而这个:
const parseConnections = connectionsCSVPath, (req, res) => {
//do a bunch of stuff
}
他们都会抛出错误。将这 3 个参数传递给函数以便在内部定义所有 3 个参数的正确方法是什么?
编辑*:然后像这样调用该函数:
router.post(
'/upload/engagements/batch', checkIfAuthenticated,
parseConnections('./tmp/connections.csv'),
parseMessages('./tmp/messages.csv'), (req, res) => {
//do a bunch of stuff
}
问题不在于如何定义函数,而在于如何使用它。
parseConnections('./tmp/connections.csv')
立即调用该函数。您只向它传递一个参数,因此req
和res
将被undefined
。
function foo(a, b, c) {
console.log('a:', a);
console.log('b:', b);
console.log('c:', c);
}
foo('first argument');
但是,不能传递req
和res
的值,因为这些值是由表达式本身创建和传递的。
从本质上讲,您犯了一个错误,即在应该传递函数的位置调用函数。router.post
期望传递一个或多个函数。但是您正在调用parseConnections
并传递其返回值,这可能是undefined
.
下面是一个演示差异的简单示例:
function foo(x) {
console.log('inside foo', 'x is ', x);
}
// bar expects to be passed a function that it can call
function bar(callback) {
console.log('bar received:', callback);
try {
callback(42);
} catch(e) {
console.error(e);
}
}
// this will work as expected
console.log('Passing a function');
bar(foo);
// this will error because `bar` doesn't receive a function.
// this is what you are doing
console.log('Calling a function and passing its return value');
bar(foo(21));
解决问题的一种方法是使parseConnections
返回一个函数,然后由router.post
接收。我在这里使用普通的函数声明,以便语法不会太混乱:
function parseConnections(connectionsCSVPath) {
return function(req, res) {
//do a bunch of stuff
};
}
这不需要更改您的router.post
呼叫。
另一种解决方案是将一个函数传递给调用parseConnections
的router.post
,传递req
和res
:
router.post(
'/upload/engagements/batch',
checkIfAuthenticated,
(req, res) => parseConnections('./tmp/connections.csv', req, res),
// alternatively you can use `.bind`:
// parseConnections.bind(null, './tmp/connections.csv'),
parseMessages('./tmp/messages.csv'), // <- this is likely wrong as well,
// but I leave this to you to figure out
(req, res) => {
//do a bunch of stuff
}
);