app.use((ctx, next) => {
const start = new Date;
console.log('app 1')
return next().then(() => {
const ms = new Date - start;
console.log('app 1 callback')
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
});
app.use(async (ctx, next) => {
const start = new Date;
console.log('app 2')
await next();
const ms = new Date - start;
console.log('app 2 callback')
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
app.use(ctx => {
console.log('app 3')
ctx.body = "hello KOA";
});
app 1
app 2
app 3
app 2 callback
GET / - 3ms
app 1 callback
GET / - 7ms
刚开始学习 koa2 ,想问一下为什么 ctx.body = 'xxx' 会到最后才执行呢,它看起来明明就是一个同步方法,用 promise 理解也就是
return next().then(() => {
//
return next().then(() => {
//
return next().then(() => {
ctx.body = 'xxx'
// 那这一步应该会直接执行才对
})
})
})