ES6 Generator
Basic Usage of Generator
Generator is an asynchronous solution provided by ES6. What can it do?
What specific problems can it solve for us?
For example, let’s say I need to do something, but it requires two ajax calls to complete first.
For instance:
$http.get('request 1').success(function(){
$http.get('request 2').success(function(){
// do something ...
})
})
This approach requires nested callbacks. With more requests, the code becomes very messy.
Now with Generator, how would we do it?
function* getData(){
yield $http.get('request 1').success(function(){
// do something ...
g.next();
});
yield $http.get('request 2').success(function(){
// do something ...
g.next();
});
// The final thing to do
}
var g =getData();
g.next();
This way, we’ve turned nested asynchronous operations into something that looks “synchronous.”
The function above has three key points:
There’s a
*afterfunction.There’s a
yieldkeyword inside the function.After the function executes, there’s a
nextmethod.
The basic use of Generator revolves around these three key points.
The execution process of Generator works like this:
Adding
*afterfunctiondeclares a Generator function.When the Generator function runs, it instantiates a Generator object with a
nextmethod.When we call the
nextmethod, the Generator function’s actual content starts executing.When the Generator function encounters
yield, it pauses execution.The next time
nextis called, the Generator function continues from where it last paused.
yield
The yield keyword is similar to return — it returns something.
The difference is:
yield pauses the function’s execution and must be used inside a Generator function.
return terminates the function’s execution and can be used anywhere.