2014-11-21 82 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