[英]Execution flow using next()
我是新手,對 next() 函數的機制有疑問。
請在下面的代碼中解釋執行流程。
app.param('seriesId', (req, res, next) => {
... // Check for presence of series
console.log('I am executed');
next();
setTimeout(() => {console.log('Am I executed?')}, 1000); // Prints for 100, does not print for 1000
});
app.get('/:seriesId', (req, res, next) => {
... // Call to db to get series object
res.status(200).json({series: series});
});
調用next()
將控制管道中的下一個中間件。 在您的示例中,這將是app.get
。
但是,該方法的行為不像return
語句,因此您放置的任何代碼也將被執行。
給定下面的示例,如果您要啟動服務器並導航到http://localhost:1337/foo ,日志語句將是:
const express = require('express');
const app = express();
app.param('param',(req, res, next) => {
next();
setTimeout(() => console.log('well here we are'), 1000);
});
app.get('/:param', (req, res) => {
setTimeout(() => {
console.log('executing the get');
res.status(200).send();
}, 2000);
});
app.listen(1337);
console.log('app started at http://localhost:1337');
避免混淆的一個好做法是確保在執行結束時調用next()
。 例如,不要這樣做:
if(aCondition) {
next()
}
next(new Error('Condition was false'));
但是做:
if(aCondition) {
next()
} else {
next(new Error('Condition was false'));
}
或者,我所做的總是返回next()
調用,以避免中間件執行任何進一步的代碼。
最后一點:如果你需要在你的中間件中執行異步代碼,那么只有在這段代碼執行完后才調用next()
。
不要這樣做:
loadUserFromDB()
.then(u => req.user = u);
next();
但是做:
loadUserFromDB()
.then(u => {
req.user = u;
next();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.