Generator(异步生成器)

/异步编程: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}返回一个对象,promise

//表示执行的值,以及是否完成全部的执行任务

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
}code

相关文章
相关标签/搜索