Reputation: 497
I'm trying to write a Koa middleware, if condition met, go to next middelware. If condition unmet, short-circuit the flow. I found 2 ways, using promise or async/await.
Method 1: Promise-based
app.use(function(ctx, next){
// if condition met
if (conditionMet){
ctx.somedata = 'bar';
// go to next middleware
return next();
}
})
Method 2: Async/Await
app.use(async function(ctx, next){
// if condition met
if (conditionMet){
ctx.somedata = 'bar';
// go to next middleware
await next();
}
})
Is there any difference between these 2 methods? If there's not any, which one is preferred?
Upvotes: 1
Views: 1858
Reputation: 10695
When there's no code after await next()
, you achieve the same thing. As ippi mentioned in the comment, when having code afterwards, with await will just be "cleaner" as it will wait until the promise is resolve to go to next line, while in the "common promises way" you would have to handle the resolution of the promise. In your specific example, it doesn't matter, but probably in other parts of your code you will use one or the other (maybe in another middleware?), and you will want to homogenize your code.
In case you would have something afterwards you would do it this way (probably you already know):
async functions (node v7.6+)
app.use(async (ctx, next) => {
// if condition met
if (conditionMet){
ctx.somedata = 'bar';
// go to next middleware
await next();
// after code
console.log('this will be executed after promise next() is resolved');
}
});
Common function
app.use((ctx, next) => {
// if condition met
if (conditionMet){
ctx.somedata = 'bar';
// go to next middleware
return next().then(() => {
// after code
console.log('this will be executed after promise next() is resolved');
});
}
});
I cannot say there is a better one, they are just different. For me async/await looks clenaer and I can personally control better the flow of the code and avoid Promises Hell. I think they are getting stronger and supported by the new javascript standard but for someone that started coding with js maybe original promises looks better...
Upvotes: 2