2014-11-21 146 views
-1

我正在使用Expressjs和Mongoosejs。我的路线是这个样子:router.use中的异步操作

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.get代码之前在router.use异步功能将解决?

回答

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

有用的链接:

+0

干杯此! – tommyd456 2014-11-21 22:26:34