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:

  1. There’s a * after function.

  2. There’s a yield keyword inside the function.

  3. After the function executes, there’s a next method.

The basic use of Generator revolves around these three key points.


The execution process of Generator works like this:

  1. Adding * after function declares a Generator function.

  2. When the Generator function runs, it instantiates a Generator object with a next method.

  3. When we call the next method, the Generator function’s actual content starts executing.

  4. When the Generator function encounters yield, it pauses execution.

  5. The next time next is 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.

Article Link:

/en/archive/es6-generator/

# Related Articles