Avoid Callback Hell in Angular Code
“When your codebase smell like hell then one of the reasons is callback hell” — Me😎
Jokes apart, a new programmer often tends to write such cozy code just after finishing his training. Let's have a look.
We call an API and get data from the backend. Such code is linear as there is no nesting(call within call) Easy! but real world is not as easy. Now requirement says once you get user’s data then you must call another API fetching its posts. A newbie will write code as below.
You can see I wrote my second API call into subscribe of first one. Imagine we call few more APIs like this. Readability of code would be worsen because linearity of code is compromised. The calls are nested and calling APIs(or code) in such nested way is called callback hell.
If we have another such dependent call, it will start shaping a real hell.
Now if we somehow manage to remove callback hell our code will be linear and easier to understand for anyone. This is done by using higher order RxJX operators. Lets see how can we solve the problem.
Now code is linear and easier to understand. The nesting is solved by higher order RxJS flattening operators like concatMap, flatMap, mergeMap or switchMap. To understand “Higher Order Operators ” more I have another blog for that here.
I hope it was pretty clear. In case of any doubt please leave comments.Please do subscribe/clap/like as it gives me an impetus for writing more such blogs.
I’ve created an Angular Course on Udemy which covers many practical problems and solutions in Angular including this one. It could be a stepping stone in your professional Angular Journey. Please take a look.
You can also watch/subscribe my free YouTube channel.
Please subscribe/follow/like/clap.