我正在使用Express Js和Mongoose Js。我的根看起来像这样:
router.use('/', function(req, res, next) {
//check for matching API KEY in database for all routes that follow
//Asynchronous Mongoosejs find.one
}
router.get('/status/:key/:token', function (req, res) {
//more code here that needs to wait before being executed
}
只是想知道router.use
中的异步函数是否会在router.get
代码执行之前解析?
答案 0 :(得分:0)
只要你正确使用next()
示例:
router.use('/', function(req, res, next) {
somethingAsync(function(err, result) {
if(err) return next(err);
// Do whatever
return next();
});
});
路由器堆栈在添加路由的顺序中被调用。调用next()
会调用堆栈中与提供的路径匹配的下一个路由。
调用next(someError)
调用堆栈中的下一个错误处理路由。
错误处理路由有4个参数而不是3个。
错误处理路径示例:
router.use(function(err, req, res, next) {
res.status(500);
return res.send('500: Internal Server Error');
});
有用的链接: