Reputation: 2741
The documentation outlines the use-case for using 'await next()' in middleware, causing the middleware to pause and trigger the next middleware downstream until all middlewares are done executing at which point the upstream cascade will begin and the middlewares will complete execution. And if a user wants to cut the cascade short then writing 'return' alone will cut the cascade all together.
What I don't understand is what happens if the user returns one of the following:
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');
};
In the first example, I think it will pause, trigger the next middleware, but will not finish the execution on the upward cascade.
In the second example, I think the next middleware will be triggered along with the console.log, I don't think it will trigger on the upward, maybe?
In the third example, I think the next middleware will be triggered but it will not trigger the console log on the upward cascade, the same as the first example.
Is my thinking correct? I'm writing a koa app and would like to learn more about its limits and I find this one area I don't understand clearly.
Upvotes: 3
Views: 3965
Reputation: 33
some more to answer of NV4RE,
const exampleMiddleware4 = async (ctx, next) => {
await next();
console.log('Doing something');
};
Here console.log will wait till the next middleware fufiled if it return promise.
Upvotes: 0
Reputation: 193
exampleMiddleware1 and exampleMiddleware3 is the same (no need to return await unless you want to catch error before return)
exampleMiddleware2
If next middleware return promise
If next middleware not return promise
Upvotes: 4