Monthly Archives: August 2015

Promise chain in Javascript

Promise is very useful in Javascript to eliminate callback hell, but in some case writing promise still seems lengthy. It is very common for me to have a pattern like below

Basically, i want to get the result of the current promise and call an immediate function which returns another promise and so on. It would be great if we can reduce the callback part in the promise and can just use method chaining. (Note: This can be also solved very nicely with generator, but i want to try something new.)

Of course the above code will fail immediately because it will try to call an undefined function on the returned promise. It is like underscore chain function. What if we can catch up all the functions and replay it as promise.
After some help from Google, It turns out that ES6 Proxy can help you to achieve promising chaining. I do a proof of concept implementation of the idea so you can use chain() to chain promise results. Chain will create a Proxy and collect all the called function and when finally() is called, it will replay all the called functions to the promise and return another promise. The code will now look like this with promise chaining:

Now the code just looks like regular  chaining  code. You can also use this with coroutine library like co or Bluebird because it also returns a promise. Pretty cool, huh!

Just a note for you that this implementation is purely for testing and for sure it has a lot of bug, don’t use it for real. Also a side note that Proxy is not yet available in node.js or io.js yet (sigh …), and only Firefox and Internet Explorer 12 support Proxy now. Proxy can’t also be polyfilled due to the limitation of ES5.