2016. július 6., szerda

Demistfying co

I always wondered why generator functions are included in the JS language, and still don't see why they are very powerful. However one of the key reasons I still think they are a needed step for the evolution of the language is the use-case of this very article.
I am not going to talk about generator functions or Promises or the Fetch API in this article, but you can read for more information in the links I attached.
The following code snippet is basically what co package does where you can easily do asynchronous calls in a synchronous way. (the key difference here is co can deal with not only Promises, but here we just wanted to work with them, not like e.g. thunks, which co can handle).
Enough with the chit-chat, let's see some code!
The first thing what you should feel here is it has a synchronous feeling when it does something asynchronous. Witchcraft!
Let's see what is happening here (click on "Next" and "Prev" to follow the steps of the control flow)



See the Pen Demistifying co by Adam Nagy (@nagyadam2092) on CodePen.
I think this whole topic is more about to move on to the next generation asynchron call methodology, which is called async-await and thus it is a needed step to be able to build that kind of behaviour.
BTW it's fun to have a look at what an ES6 transpiler is doing with this code-snippet, go on and try it here: https://babeljs.io/repl/
In summary I think we achieved a good (not great) way of handling asynchronous calls with a "synchron-like" feeling.