ES6 Generator函数
- 该函数是一个状态机,内部封装不同状态的数据
- 用来生成并返回一个遍历器对象,必须通过该遍历器对象.next()执行函数
- 可暂停函数,yield暂停,next启动,返回yield之后的表达式结果
- 可以让异步任务按同步方式进行,如ajax请求
返回值相关:
- 函数return 返回的值会作为最后一个迭代器遍历的结果
function* g2() {
yield 1;
return 2;
}
let it = g2();
console.log(it.next());
console.log(it.next());
//{ value: 1, done: false }
//{ value: 2, done: true }
- iterator.next(传入值);传入值可作为上一个yield的返回值,因为.next()调用是在上一个yield处调用
- 如果不传递,yield将返回undefined
- 手动结束遍历:iterator.return(数据); 会返回数据,并结束之后的所有遍历
yield相关
- 若yield后是一个Generator函数,则遍历器对象会进入Generator函数内进行遍历,遍历完成后再回到自身函数继续遍历
function* gen1() {
yield 1;
yield* gen2();
yield 4;
}
function* gen2() {
yield 2;
yield 3;
}
var g = gen1();
console.log(g.next()) { value: 1, done: false }
console.log(g.next()) { value: 2, done: false }
console.log(g.next()) { value: 3, done: false }
console.log(g.next()) { value: 4, done: false }
console.log(g.next()) { value: undefined, done: true }
- yield* 表达式,如果yield后加* ,则迭代器value的结果将会是后面表达式的迭代器,如果后面不是可迭代对象,则会报错
function* gen1(){
yield ["a", "b", "c"]
}
for(let val of gen1()){
console.log(a)
}
// ["a", "b", "c"]
function* gen2(){
yield* ["a", "b", "c"]
}
for(let val of gen2()){
console.log(a)
}
// a b c
错误抛出相关
- 通过迭代器.throw()可抛出错误,传入的参数可被try-catch使用,其他功能和next相同
- 当迭代器未遍历时,只会抛出外部的错误
function* foo() {
try {
let c = yield "hahaha";
console.log(c);
} catch (err) {
console.log("inside error: " + err);
}
return 2;
}
var it = foo();
try {
console.log(it.throw(5));
} catch (err) {
console.log("out error: " + err);
}
//out error: 5
function* foo() {
try {
yield "hahaha";
} catch (err) {
console.log("inside error: " + err);
}
return 2;
}
var it = foo();
try {
console.log(it.next());
console.log(it.throw(1));
} catch (err) {
console.log("out error: " + err);
}
//{ value: 'hahaha', done: false }
//inside error: 1
//{ value: 2, done: true }
- 会跳过当前的yield,去执行下一个yield
var foo = function* foo() {
try {
yield 222;
yield 333;
} catch (e) {
console.log("inside err");
}
yield console.log("3");
yield console.log("4");
};
var g = foo();
console.log(g.next());
console.log(g.throw());
g.next();
//{ value: 222, done: false }
//inside err
//3
//{ value: undefined, done: false }
//4
代码示例:
<html ng-app='app' ng-controller='main' >
<head>
<meta charset="utf-8">
<meta name='viewport' content='width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0'>
<script src='jq/jquery-3.4.1.js'></script>
<style>
</style>
</head>
<body >
<script>
function *fun()
{
console.log('开始');
let call=yield 'hello';
console.log(call);
console.log('过程');
yield 'generator';
console.log('结束');
return '结束';
}
let ite=fun();//返回遍历器对象
console.log(ite.next());
console.log(ite.next('返回值'));
console.log(ite.next());
</script>
</body>
</html>