Generator:
创建:
function* g() {} // g: [object Generator]
let g = function*() {};
let obj = {
*g() {}
};
const generatorName = ‘g‘;
let obj = {
*[generatorName]() {}
};
const generatorName = ‘g‘;
class Klazz {
*[generatorName]() {}
}
iterator:
const generatorFunction = function* (){
yield 1;
yield 2;
};
let generator = new generatorFunction();
typeof generator // object
typeof generator[Symbol.iterator]; // function
let a = ‘‘;
function iterateForOf(){
for (let value of generator) {
a += value; // a: ‘12‘
}
}
yield:
function* generatorFunction() {
yield ‘hello‘;
yield ‘world‘;
}
let generator = generatorFunction();
let values = Array.from(generator); // [‘hello‘, ‘world‘]
let thisStep = generator.next();
let [value, done] = [thisStep.value, thisStep.done]; // hello, false
let thatStep = generator.next();
let [value, done] = [thisStep.value, thisStep.done]; // world, false
generator.done // true
function* fibonacci() {
let a = 0, b = 1;
//1, 2
while(true) {
yield a;
a = b;
b = a + b;
}
}
参数:
function* generatorFunction(v) {
yield v;
}
let iterator = generatorFunction(3);
assert.equal(iterator.next().value, 3);
assert.equal(iterator.next(2).value, 2);
});
function* ticketGenerator(){ // 不断递增,知道.next传入true
for(var i=0; true; i++){
var reset = yield i;
if(reset) {i = -1;}
}
}
替代callback:
function run(generatorFunction) { var generatorItr = generatorFunction(resume); function resume(callbackValue) { generatorItr.next(callbackValue); } generatorItr.next()
}
run(function* myDelayedMessages(resume) {
console.log(yield delay(1000, resume));
console.log(yield delay(1200, resume));
})