【发布时间】:2019-10-28 00:28:04
【问题描述】:
以下是我的设置,我试图将在 express 中间件中初始化的对象传递给不同的中间件函数。在我的路由器中,调用 helper.getValues() 并得到一个错误,我无法调用未定义的函数 getValues
let helper; // no initial value
const getConfig = async () => {
config = await service.getConfig(configName);
helper = new Helper(config); // Helper is correctly initialized here
};
// declare a new express app
let app = express();
app.use(async function (req, res, next) {
try {
await getConfig(); // invoke the code that initializes my helper
next();
} catch (e) {
console.error(e);
}
});
app.use('/path', MyRouter(helper)); // Pass helper to router - it's undefined in router code
我的路由器构造函数如下所示
function MyRouter(helper) {
...
... const values = helper.getValues();
}
将 getConfig 中创建的帮助程序传递给我的路由器的正确方法是什么?
【问题讨论】: