如何在express中导出路由器内部的异步函数



我在index.js文件中有以下路由-

router.post(/login, async (req,res) => {
async function getUser(id, data){
... Some logic
}
})

我如何导出这个函数,以便导入它并从另一个文件调用,即register.js,它有自己的路由。?已尝试module.exports=getUser((但它说它没有定义。

尝试在路由器处理程序函数之外定义函数

async function getUser(id, data){
... Some logic
}
router.post(/login, async (req,res) => {
// getUser should be accessible inside here
})
module.exports = getUser

为了适应您提到的getUser将调整要导出的传入res数据的注释/编辑,我们需要在getUser函数之外定义一个状态对象。至少从功能的角度来看,这是可行的,但我相信有更好的方法来整理它:

let state = {}
async function getUser(id, data){
// Some logic
// use res here by accessing the state object
}
router.post(/login, async (req,res) => {
// getUser should be accessible inside here
state = res;
})
module.exports = getUser

最新更新