Photo by Karine Avetisyan on Unsplash 路 21/2/2016
$q promises for angular are not only good for async tasks but an incredible way to write clean and readable code.
Since a few months, I鈥檝e decided to write my code in very small functions with its in/out parameters and its detailed documentation.
Maybe you are not following the relation between $q promises and organizing the code in small-low-complex functions. I鈥檓 explaining myself.
Once you understand the way promises work (Ben Nadel wrote an incredible article about them) you can use promise chaining to execute different steps of your code, capture errors and avoid a pyramid of doom.
Let me show you how. Code below represents a method that activates a user, following next steps:
https://gist.github.com/adgllorente/4f5b45385b3800b9e28c
I鈥檓 not going to explain what is this code for, but resuming it, it performs some requests to an API, apply some filters, controls different error codes and finally assigns data to $scope to be painted in the interface.
What draws attention in the code above is:
Here is where promise chaining is going to make a difference.
Let鈥檚 see code below, the result of its execution is the same but more readable and organized. I鈥檝e split previous activate function into different small functions: getUser, enableUser and getUserToken. Each small function is doing its work, resolving data or rejecting its error codes. These functions are chained and executed inside the method activate.
https://gist.github.com/adgllorente/9c93cfac7ffa6f666b62
As you can see, code is more readable and clean, each small function might be well documented. You can use callbacks too but I love the way I can control successful/error flows just chaining then and catch ?.
路 Adri谩n G贸mez
Powered by Astro + TailwindCSS + Markdown