1. Overview
generator is a new data type introduced by ES6. It looks like a function. In addition to using return, yield can be returned multiple times.
generator is defined by function*, (note * number),
2. Example
Functions cannot save state, and sometimes global variables are needed to save numbers;
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 < 100; x ++) { if (g.next().value !== x) { pass = false; alert('test failed!'); break; }}if (pass) { alert('test passed!');}2.2 An infinite loop iterator
function* idMaker(){ var index = 0; while(true) yield index++;}var gen = idMaker(); // "Generator { }"console.log(gen.next().value); // 0console.log(gen.next().value); // 1console.log(gen.next().value); // 22.3Generator.prototype.next()
When the iteration ends, Generator.next().done ===true, before ending ===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 that if the value of done is true, and then call return, the returned value will also be 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()
The thorw() method regains the execution of the iterator by throwing an exception into the iterator;
Returns an object object with two attributes: value and done
function* gen() { while(true) { try { yield 42; } catch(e) { console.log("Error catch!"); } }}var g = gen();var a = g.next();// { value: 42, done: false }var b = g.throw(new Error("Something went wrong"));// "Error catch!"// { value: 42, done: false }console.log(a);console.log(b.value+"::"+b.done);The above article in-depth understanding of the js generator data type is all the content I have shared with you. I hope you can give you a reference and I hope you can support Wulin.com more.