Avoid Callback Hell in Angular Code

Pawan Kumawat
2 min readFeb 10, 2022

--

“When your codebase smell like hell then one of the reasons is callback hell” — Me😎

Callback Hell

Jokes apart, a new programmer often tends to write such cozy code just after finishing his training. Let's have a look.

Call Back Hell

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.

Call back hell

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.

Real Callback 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.

Solve Callback hell

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.

Angular-Practicals
Angular-Practicals

You can also watch/subscribe my free YouTube channel.

Please subscribe/follow/like/clap.

--

--

Responses (5)