router.use中的异步操作

时间:2014-11-21 21:56:08

标签: node.js express

我正在使用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代码执行之前解析?

1 个答案:

答案 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');
});

有用的链接: