![](/img/trans.png)
[英]Difference between async(req,res,next) and async(req,res,()=>{}
[英]abstract (req, res, next) in node
说我有一条路线:
app.get(abc, (req, res, next) => {
if (req.params.ID === undefined) {
res.status(400);
res.end();
}
next();
});
我想知道如果我将if语句抽象到另一个文件中是否也能如此工作:
let undefinedID = (req, res, next) => {
if (req.params.ID === undefined) {
res.status(400);
res.end();
}
next();
}
module.exports = {undefinedID};
然后在我的路线内调用该函数:
const reqConditionals = require('path/to/fxn');
app.get(abc, () => {
reqConditionals.undefinedID();
});
我想要这样做的原因是因为我有很多路由具有类似的请求条件和响应,并希望开始对其进行重构。 因此,如果我这样操作,是否会一样工作?
是的,你可以这么做。 但是你这样做是这样的:
const reqConditionals = require('path/to/fxn');
app.get(abc, reqConditionals.undefinedID);
然后,您可以拥有实际的路线。
app.get(abc, reqConditionals.undefinedID);
app.get(abc, (req, res, next) => {
//here you know that the id is not undefined cause the previous middleware let you reach here.
});
此外,您可以将其应用于数组或其他任何功能,并具有多个功能。
app.get([abc, def], reqConditionals.undefinedID, reqConditionals.undefinedFoo, reqConditionals.undefinedBar);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.