/异步编程:Generator(生成器):在异步对象promise之后的*/
//Generator中包含了多种状态,通过yield进行返回 eg://
function* hello(){
yield 'hello'; //状态一
yield 'world'; //状态二
return 'ending';//完结状态
}
/插入一个知识点/
//var test =hello;
// console.log(test().next());//hello
// console.log(test().next());//hello
///???因为test(),每次运行都会取到一个指向终点的指针,再next()都是指向第一个 yield,所以值都是’hello’
//var ho =hello(); ho.next():每次都是用的一个指针在静止,所以能够遍历。
/*/
var ho =hello()//该生成器运行返回指向 yield ‘hello’的指针对象,没有开始执行
//2.执行程序:会在yield 前进行执行,通过next来执行
console.log(ho.next())//{value:’hello’,done:false}返回一个对象,
//示意执行的值,以及是否实现所有的执行工作
console.log(ho.next());//{value:’world’,done:false};
console.log(ho.next());//{value:’ending’,done:true};//执行到return或者最初一个yield(判断无值),done就是true
console.log(ho.next());
//3 yield.next()办法传递参数:给上一个yield赋值
//个别状况下 eg:
var step_1,step_2;
function* test_eg(){
step_1=yield 'xmj';
step_2=yield '666';
return '!';
}
console.log(step_1);//示意yield最开始都是undefined;
//通过 yield.next(赋值的参数)为上一个赋值是为yield xx这个表达式赋值,不能多也不能少
var test_eg =test_eg();
test_eg.next();//最开始step_1下面没有yield 赋值没有意义
test_eg.next(‘这是给上一个yield表达式赋值’);
console.log(‘step_1: ‘+step_1);//step_1:这是给上一个yield表达式赋值
/yield.next()退出参数的作用:给生成器外部赋值/
function* foo(x) {
var y = 2 * (yield (x + 1));
var z = yield (y / 3);//通过next传递参数来扭转本次的行为
return (x + y + z);
}
var a = foo(5);
a.next() // Object{value:6, done:false}
a.next() // Object{value:NaN, done:false}
a.next() // Object{value:NaN, done:true}
var b = foo(5);
b.next() // { value:6, done:false }
b.next(12) // { value:8, done:false }//把12赋值给上一个yield(x+1),所以y=2*yield(x+1)=24
b.next(13) // { value:42, done:true }
/简略向生成器外部赋值*/
function* dataConsumer() {
console.log(‘Started’);
console.log(1. ${yield}
);
console.log(2. ${yield}
);
return ‘result’;
}
let genObj = dataConsumer();
genObj.next();// Started
genObj.next(‘赋值xmj到上一页yield’)// 1. 赋值xmj到上一页yield
genObj.next(‘b’)// 2. b
/for of 快捷的遍历办法:取代next()**/
function* foo() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
return 6;
}
for (let v of foo()) {//foo()取到一个指针
console.log(v);//1,2,3,4,5 //当这个 of办法遍历到done:true时会进行,所以不会输入6
}