ES6 新引入了 Generator 函数,可以通过 yield 关键字,把函数的执行流挂起,为改变执行流程提供了可能,从而为异步编程提供解决方案。
Generator 有两个区分于普通函数的部分:
一:是在 function 后面,函数名之前有个 * ;
二:函数内部有 yield 表达式。
下面通过一个小demo演示下Generator 函数的用法
// 定义一个fun生成器函数
function* fun() {
console.log("one");
yield '1';
console.log("two");
yield '2';
console.log("three");
return '3';
}
// Generator 函数的执行机制与普通函数的执行机制不同,它不会立即执行,并且要通过迭代器的next方法才能调用函数内部的值
var f = fun();
f.next();//one
f.next();//two
// 第一次调用 next 方法时,从 Generator 函数的头部开始执行,先是打印了 one ,执行到 yield 就停下来,并将yield 后边表达式的值 '1',作为返回对象的 value 属性值,此时函数还没有执行完, 返回对象的 done 属性值是 false。
// 第三次调用 next 方法时, 此时函数已经执行完了,所以返回 value 属性值是 undefined ,done 属性值是 true 。
return 方法返回给定值,并结束遍历 Generator 函数。
return 方法提供参数时,返回该参数;不提供参数时,返回 undefined 。
function* foo() {
yield 1;
yield 2;
yield 3;
}
var f = foo();
console.log(f.next()); // {value: 1, done: false}
console.log(f.return("foo"));// {value: "foo", done: true}
throw 方法可以再 Generator 函数体外面抛出异常,再函数体内部捕获。
var g = function* () {
try {
yield;
} catch (e) {
console.log('catch inner', e);
}
};
var i = fun();
i.next();
try {
i.throw('a');
i.throw('b');
} catch (e) {
console.log('catch outside', e);
}