Skip to main content

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.

  • Aral Roca Gomez

    You also can use curry method in lodash 🙂 But fundamentaly do the same that the 3 option, but clearer

  • Yep! _.curry would do the same but even more powerful and configurable.

  • someone235

    You have to bind console.log, like this .then(console.log.bind(console)). Otherwise it won’t work.

  • It is not needed because console.log is expecting just a parameter. I’ve uploaded a Codepen to see the example working: http://codepen.io/adgllorente/pen/ONpYJv

  • Sylvain Pollet

    It is not needed because of $q implementation. ES6 promises will throw a Illegal invocation exception. Try

    (new Promise(resolve => resolve(42))).then(console.log)

    vs

    (new Promise(resolve => resolve(42))).then(n => console.log(n))

  • You’re right, I thought @someone235:disqus was talking about $q and not about ES6 promises.

  • someone235

    Interesting, how does $q knows to bind it to console?

  • Nice article dude 🙂