A Generator is a function which doesn’t necessarily run to the end when we execute it but yields certain values each time you call it. This closely resembles the behavior of iterators where you also yield or get one value after the other.

A generator looks like a normal function but with a preceding satiric before the function name and the yield statement.

function *getWords() {
  yield 'Book';
  yield 'Person';
}

getWords()) // gets an iterator buts trying to print from it will prints nothing

console.log(getWords());  // [object Generator] { ... }

By running a generator we actually get back an iterator. We get back an object for which we can loop.

function *getWords() {
  yield 'Book';
  yield 'Person';
}
let iterator = getWords();

console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());

Prints:

[object Object] {
  done: false,
  value: "Book"
}
[object Object] {
  done: false,
  value: "Person"
}
[object Object] {
  done: true,
  value: undefined
}

By running iterator.next()) three time I’m lopping through those yielded values and that’s possible because of generators. Generators allow us to create a logic state and a function to yields different values, which can be use later by an iterator to loop through those values.

Example:

let canIterateObject = {
  [Symbol.iterator]: gen
}

function *gen() {
  yield 1;
  yield 2;
  yield 3;
}

for(let obj of canIterateObject) {
  console.log(obj);
}
prints: 
1
2
3

As you see Generators are really powerful and offers us new tools to do things as the ability to paused in the middle of a function, one or many times, and resumed later, allowing other code to run during these paused periods.

Generators Allow to run

asynchronous tasks and yield those results step by step like fetching something from the server for example and then use them with an iterator in a step by step approach

Inside the generator function body, we can use the new yield keyword to pause the function from inside itself.

[vc_custom_heading text=”Controlling iterators and generators with Throw:
“]
function *gen2(input) {
  for (let i = 0; i < input; i++) {
       try {
         yield i;
       } catch (e) {
         console.log(e);
       }
  }
}

let iterator2 = gen2(3);

console.log(iterator2.next());
console.log(iterator2.throw('An error ocurred!!'));
console.log(iterator2.next());
console.log(iterator2.next());
//prints:

[object Object] {
  done: false,
  value: 0
}

"An error ocurred!!"

[object Object] {
  done: false,
  value: 1
}
[object Object] {
  done: false,
  value: 2
}
[object Object] {
  done: true,
  value: undefined
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here