Es6 Generators
Generators provide a way of almost working infinitely so we can calculate
massive numbers because of the way it generates this work. Generators let us
jump through each step to generate these big numbers.
Potentially, generators let us work with asynchronous code as if it was
synchronous (avoid callback-hell).
Consider a typical example from Node land where we are using some module to
connect to our database and query for things:
Person.findOne({id: 5}, (per) => {
Location.findOne(..., (log) => {
...
});
});
This is a trivial example, but in the real world, we often have scenarios where
we have to nest callbacks several levels deep. This is make the code harder to
understand. This is known as "callback hell". We can avoid callback hell by
using Promises. We can also avoid callback hell using generators. Let's see
how generators work.
var per = yield Person.findOne(...);
var loc = yield location.findOne(...);
The above code is asynchronous but reads as synchronous.
This does not work out of the box currently. However, if you are using a
library that does support this, we can use the yield keyword, which basically
yielding to Person.findOne and location.findOne and just waiting for them to
responde. When they respond, it comes back and assigns the right data to the
right variables.
page revision: 0, last edited: 19 Feb 2017 23:13