Guard Clause in Async

I really like Guard Clause, it makes me easier to read coding flow. Ya, you might want to google it “Guard Clause”, is a pattern to write code. You’ll end up on this link: Replace Nested Conditional with Guard Clauses – Refactoring. If you don’t use it or even don’t know it yet, I suggest you to learn and use it and share to your team. You all will love it.

But, when it comes to javascript, its always be exhausted. Javascript is exhausting. I dive in to async world in javascript two years ago and still don’t know to use Guard Clause in it. Ya, this code won’t work whatsoever:

So, how do we do that ? I don’t think we can do “Guard Clause” for async.

Lets take example for Martin Fowler website above, but in js.

If functions deadAmount, separatedAmount, retiredAmount and normalPayAmount are Promises, I used to do it like this.

Ya but actually we can do it better like this.

Or better better, we can use IIFE if getPayAmount doesn’t necessary to be reusable function.

Discussion