AngularJS Coding Javascript

To bind nor not to bind

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:

  1. Using an anonymous function to chain our second promise
  2. Use “bind”  to pass the second parameter to our second function
  3. Wrap our second function into another function and chain this wrapper instead.

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.