ES6 ~ Generators - rohit120582sharma/Documentation GitHub Wiki

Functions that can return multiple values at different time interval, as per the user demands and can manage its internal state are generator functions. A function becomes a Generator Function if it uses the function* syntax.

Generators functions can be exited and later re-entered. Their context (variable binding) will be saved across re-entrances.

Calling generator function does not execute its body. Instead, you get a iterator object, with which you can control the execution of the body. The pause and resume are done using yield & next.

The method call iterator.next() continues execution until the next yield.

References


yield / *yield

Yield is a special keyword that appears only inside generator functions. It is often proceeded by a function call that returns a promise.

The yield expression is used to pause the function and give out a value. The yield can take in a value when we restart the function. The yield is used to delegate to another outside generator function.

Once paused on a yield expression, the generator's code execution remains paused until the generator's next() method is called. Each time the generator's next() method is called, the generator resumes execution and return the iterator result.


How to run the function*

  • We first invoke the function and store it in a variable
  • The invocation of the function returns an iterable object back
  • We can call next on this object to take us to the first yield point in the function
  • This call will give us back an object with the properties of value and done
  • The done indicates a true/false on whether the function is completed
  • We can continue iterating through this until we are done or stop at any point

Examples

function* foo(){
	let x = yield 'Please give me a value of x';
	console.log(x); // 8

	let y = yield 'Please give me a value of y';
	console.log(y); // 17

	let z = yield 'Please give me a value of z';
	console.log(z); // 25

	return (x + y + z);
}

// return a iterable object and store in generatingFoo
let generatingFoo = foo();

// {value: "Please give me a value of x", done: false}
generatingFoo.next();

// Store the result you pass in into x
// {value: "Please give me a value of y", done: false}
generatingFoo.next(8);

// Store the result you pass in into y
// {value: "Please give me a value of z", done: false}
generatingFoo.next(17);

// Store the result you pass in into z
// {value: 50, done: true}
generatingFoo.next(25);
function request(url){
	makeAjaxCall(url, function(response){
		it.next(response);
	})
}

function* main(){
	var result1 = yield request('http://some.url.1');
	var data = JSON.parse(result1);

	var resulr2 = yield request('http://some.url.2?id=' + data.id);
	var resp = JSON.parse(result2);

	console.log('The value you asked for: ' + resp.value);
}

var it = main();
it.next(); // Get it all started

⚠️ **GitHub.com Fallback** ⚠️