Photo by Womanizer WOW Tech on Unsplash · 21/3/2016
If you have read my previous article about chaining promises, you’ll know I love using small functions in “then” methods, but sometimes chaining is not that simple.
For example, when you have to execute in your “then” method a function receiving two parameters it is not possible… or it is?
In these cases you can use some alternatives as seen below:
I have to say that alternatives 2 and 3 are almost the same because as you can read in Mozilla the method “bind” wraps a given function and allows us to set a “this” to be used inside that function, but as we are not setting a “this” we are writing null every time we use it, and this is something I don’t really like.
In conclusion, after having used three of them, I think the best solution is using the first alternative and chain an anonymous function with “sumTwoNumbers” executed inside, but please, if you want to continue chaining promises, do it in the anonymous function as I’ve done with the console.log and not in the sumTwoNumbers because one the most important rules is Write code easy to read and pyramids doesn’t make it more readable.
Update (22/03/2016): Codepen created.
· Adrián Gómez
Powered by Astro + TailwindCSS + Markdown