我在async/await中使用koa2,如下所示
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
await next()
console.log("1------>"+Date.now())
});
app.use(async (ctx, next) => {
await next()
console.log("2------>"+Date.now())
});
app.use(async (ctx, next) => {
await next()
console.log("3------>"+Date.now())
});
app.use(async (ctx, next) => {
await next()
console.log("4------>"+Date.now())
});
app.listen(3000);运行这段代码,我会得到这样的日志
4------>1526575713792
3------>1526575713794
2------>1526575713795
1------>1526575713795以下是我的问题
next in app.use(async (ctx, next)是什么,是函数吗?await next()在每个app.use函数中的意思是wait, please run the next app.use first,如果没有下一个app.use,忽略它,然后在最后一个app.use函数中运行代码,对吗?app.use更改为app.use(async (ctx) => { console.log("1------>"+Date.now())});,并运行它,结果只有一个记录1------>1526576945380。我以为第二个app.use函数会继续运行,我会得到这样的结果
1->1526576945360
4->1526575761869
3->1526575761869
2->1526575761869有人能帮我吗?给我解释一下?非常感谢。
发布于 2018-05-17 17:25:20
next是一个函数,console.log(typeof next)会向您展示这一点。next将指示koa执行使用use注册的下一个中间件,并返回一个承诺,即一旦下一个中间件解析,await就会出现在该next前面,您的代码将在那里等待,直到该承诺被解析。use中注册的下一个中间件被调用?您不调用next,所以在这个中间件中终止。await是一种js功能,用于等待承诺得到解决。next是执行下一个中间件的koa功能。https://stackoverflow.com/questions/50397110
复制相似问题