Koa中await next()、return await next()、return next()、中间件中的next()有什么区别?
In Koa, what's the difference between await next(), return await next(), return next(), and next() in middleware?
文档概述了在中间件中使用 'await next()' 的用例,导致中间件暂停并触发下游的下一个中间件,直到所有中间件执行完毕,此时上游级联将开始并且中间件将完成执行。如果用户想要缩短级联,那么单独编写 'return' 将一起切断级联。
我不明白的是如果用户 returns 以下情况之一会发生什么:
const exampleMiddleware1 = async (ctx, next) => {
return await next();
console.log('Doing something');
};
const exampleMiddleware2 = async (ctx, next) => {
next();
console.log('Doing something');
};
const exampleMiddleware3 = async (ctx, next) => {
return next();
console.log('Doing something');
};
在第一个例子中,我认为它会暂停,触发下一个中间件,但不会在向上级联上执行完。
在第二个例子中,我认为下一个中间件会随着console.log一起触发,我认为它不会在向上触发,也许吧?
第三个例子,我觉得会触发下一个中间件,但是不会触发上级联的控制台日志,和第一个例子一样
我的想法对吗?我正在编写一个 koa 应用程序,想了解更多有关它的限制的信息,但我发现这一领域我不太了解。
exampleMiddleware1和exampleMiddleware3是一样的(不需要returnawait 除非你想在 return)
之前捕获错误
- 你的console.log永远不会被调用
exampleMiddleware2
如果下一个中间件return promise
- 您的 console.log 将调用而无需等待下一个中间件 fufiled
if next middleware not return promise
- 接下来会完成下一个中间件console.log
文档概述了在中间件中使用 'await next()' 的用例,导致中间件暂停并触发下游的下一个中间件,直到所有中间件执行完毕,此时上游级联将开始并且中间件将完成执行。如果用户想要缩短级联,那么单独编写 'return' 将一起切断级联。
我不明白的是如果用户 returns 以下情况之一会发生什么:
const exampleMiddleware1 = async (ctx, next) => {
return await next();
console.log('Doing something');
};
const exampleMiddleware2 = async (ctx, next) => {
next();
console.log('Doing something');
};
const exampleMiddleware3 = async (ctx, next) => {
return next();
console.log('Doing something');
};
在第一个例子中,我认为它会暂停,触发下一个中间件,但不会在向上级联上执行完。
在第二个例子中,我认为下一个中间件会随着console.log一起触发,我认为它不会在向上触发,也许吧?
第三个例子,我觉得会触发下一个中间件,但是不会触发上级联的控制台日志,和第一个例子一样
我的想法对吗?我正在编写一个 koa 应用程序,想了解更多有关它的限制的信息,但我发现这一领域我不太了解。
exampleMiddleware1和exampleMiddleware3是一样的(不需要returnawait 除非你想在 return)
之前捕获错误- 你的console.log永远不会被调用
exampleMiddleware2
如果下一个中间件return promise
- 您的 console.log 将调用而无需等待下一个中间件 fufiled
if next middleware not return promise
- 接下来会完成下一个中间件console.log