Node.js 在快速路由器和控制器逻辑之间传递变量
我试图将代码模块化,并利用从express router到包含控制器逻辑的外部模块的函数调用。在处理请求后,如何将变量传递回路由器 const express=需要“express”; const router=express.router; const bodyParser=需要“body-parser” const requestSomething=require'/controller/abc.js'; 路由器。post“/”,函数req,res,next{Node.js 在快速路由器和控制器逻辑之间传递变量,node.js,express,Node.js,Express,我试图将代码模块化,并利用从express router到包含控制器逻辑的外部模块的函数调用。在处理请求后,如何将变量传递回路由器 const express=需要“express”; const router=express.router; const bodyParser=需要“body-parser” const requestSomething=require'/controller/abc.js'; 路由器。post“/”,函数req,res,next{ requestSomethi
requestSomething在您的情况下,它是一个异步函数,您必须为此使用promise。promise是一个对象,可以由同步或异步函数返回,其中包含函数的成功和失败结果,具体取决于条件。有关详细信息,请查看 就像你的路由器:
router.post('/', function (req,res, next){
requestSomething().then(function(x){
next();
}).catch(function(onError){
}); //but the problem is, it will not wait for next. so you can use in then part
// next()
},function(req,res,next){
sendOrder(X) <--------//So I can use it further along in chain
}
);
如果我理解你的要求。
请阅读有关javascript中承诺调用的更多信息。您应该使用承诺实现异步行为。 有两个像JavaScript Promise这样的库 你可以用任何一个 假设您必须在server.js文件上编写类似的内容
router.post('/', function (req,res, next){
requestSomething().then((x)=>{
return x;
}).then((x)=>{
sendOrder(X)
}) <----// Need Variable from this
});
在中间件部分,让我们说一下您的控制器
return new Promise(function(resolve, reject) {
let options = { };
requestSomething(options, function (error, response, body) { //API Call
if (error) {
return reject(error);
}
let x = JSON.parse(body); //<--- How do I pass this back to router?
return resolve(x);
})
})
感谢您的回复我一直在尝试让它工作,但我遇到了一个错误。无法在requestSomething.then上读取未定义的属性'then'。但是函数调用确实发生。requestSomething是API调用吗?是的,它是API调用。