开发express中间件的时候遇到一个问题: 代码如下:
app.use(function(req, res, next){ next(); console.log("after next"); }); app.use(function(req, res, next){ console.log("before next"); next(); });
这里的中间件调用结果是:
before next after next
所以我认为中间件是一个栈结构,next前的代码先执行,然后执行next调用下一个中间件,最后回到当前的中间件,执行next后面的代码。 但是我写了另外一个例子,并不支持我这种理解。 代码如下:
app.use(function(req, res, next){ next(); console.log("after next") }); app.use(function(req, res, next){ process.nextTick(function(){ console.log("before next") next(); }); });
执行结果:
after next before next
请问这是什么原因?