1 回答
TA贡献1810条经验 获得超4个赞
把第二个中间件写成异步的就可以了
const test2 = async (ctx, next) => {
console.log('test2')
await next()
}
koa中间件执行后必须返回一个promise,如果非要用普通的函数写法,可以这样:
const test2 = (ctx, next) => {
return next().then(()=>{
console.log('test2')
})
}
如果你非要搞懂,可以看下这篇文章深入浅出koa2
再补充一下,不知道你看完这个能不能理解
const Koa = require('koa');
const static = require('koa-static')
const path = require('path')
const app = new Koa();
const test1 = async (ctx, next) => {
console.log('test1')
await next()
}
const test2 = (ctx, next) => {
console.log('test2')
return next().then(()=>{
console.log('test3')
})
}
const test3 = (ctx, next) => {
console.log('test4')
return next().then(()=>{
console.log('test5')
})
}
app.use(test1)
app.use(test2)
app.use(test3)
app.use(static(path.join(__dirname, 'static')))
app.listen(8080);
// 打印结果
test1
test2
test4
test5
test3
添加回答
举报