1. Overview
Generator is a new data type introduced by ES6 that looks like a function that yield can be returned multiple times except by returning with return.
Generator is defined by the function*, (note the * number),
2. Examples
function cannot save state, sometimes need global variable to save number;
2.1
' Use strict ';
function next_id () {
var id = 1;
while (id<100) {
yield id;
id++;
}
return ID;
}
Test:
var
x, pass
= True,
g = next_id ();
for (x = 1; x < x + +) {
if (G.next (). Value!== x) {Pass
= false;
Alert (' Test failed! ');
break;
}
}
if (pass) {
alert (' Test passed! ');
}
2.2 An infinite loop of iterators
function* Idmaker () {
var index = 0;
while (true)
yield index++;
var Gen = Idmaker (); "Generator {}"
Console.log (Gen.next (). value);//0
Console.log (gen.next (). value);//1
console.log ( Gen.next (). value); 2
2.3generator.prototype.next ()
When the iteration ends, Generator.next (). Done ===true, before the end ===false
Function* Gen () {
yield 1;
Yield 2;
Yield 3;
}
var g = gen (); "Generator {}"
g.next (); "Object {value:1, done:false}"
G.next (); "Object {value:2, done:false}"
G.next (); "Object {value:3, done:false}"
G.next (); "Object {value:undefined, done:true}"
2.4 Generator.prototype.return ();
The return method returns the given parameter value and ends the iterator
Example
Function* Gen () {
yield 1;
Yield 2;
Yield 3;
}
var g = gen ();
G.next (); {value:1, done:false}
g.return ("foo");//{value: "foo", Done:true}
g.next (); {value:undefined, done:true}
Note If the done value is true and then call return, the value returned is also undefined
Function* Gen () {yield 1;}
var g = gen ();
Console.log (G.next ());//{value:1, Done:false}
Console.log (G.next ());//{value:undefined, done:true}
Console.log (G.return (1)); {value:undefined, done:true}
2.5 Generator.prototype.throw ()
Thorw () method, by throwing an exception into the iterator, to regain the execution of the iterator;
Returns an object with value and two properties
Function* Gen () {while
(true) {
try {
yield;
} catch (e) {
console.log ("Error caught!");
}
}
var g = gen ();
var a = G.next ();
{value:42, done:false}
var b = g.throw (new Error ("Something Went Wrong"));
"Error caught!"
{value:42, done:false}
Console.log (a);
Console.log (b.value+ "::" +b.done);
The above in-depth understanding of JS Generator data type is small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.