Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

koa 中间件next加上await 与不加await 的差别,请教大佬

app.use((ctx, next) => {

if (ctx.path.indexOf('favicon') > -1) {
    return;
}
console.log(3)

ctx.body = 'hellow'
next() // 注意这个中间件没有 async/await,如果加上await 就是我理解的那个样子
// return;
ctx.body += 'haha'
console.log(4)

});
// 响应时间统计中间件
app.use(async(ctx, next) => {

console.log(2)

// ctx.set('Content-Type', 'text/html')
await next()
console.log(5)

});
// 响应
app.use(async(ctx, next) => {

console.log(1)

ctx.body = 'zjp'
// console.log(ctx)
await next()
console.log(7, ctx.body)
ctx.body += 'ctt'
console.log(6)

    // next()

});

控制台运行结果:
image.png
浏览器返回结果:
image.png

疑问:
为什么这句代码没有执行`
ctx.body += 'ctt'

期待结果:zjphahactt,为什么返回的是zjphaha,没有ctt呢?如果第一个中间件加上async/await 的话就是期待的结果,

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

看了koa,和compose源码才明白,koa源码中有个方法respond中,结合宏任务微任务执行顺序....最终就是这句话
if ('string' == typeof body) {

return res.end(body);

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...