一、Generator 函数
1.定义:
Generator 函数是 ES6 提供的一种异步编程解决方案。
2.语法:
1)function关键字与函数名之间有一个星号(*);
2)函数体内部使用yield语句,定义不同的内部状态。
// 定义一个最简单的generator函数function* helloWorldGenerator() { yield 'hello'; yield 'world'; return 'ending';}3.Generator函数的神奇之处
1)helloWorldGenerator()并不执行这个函数。返回的并不是函数运行结果,而是一个指向内部状态的指针对象,也就是迭代器对象(Iterator Object)。
2)分段执行。
// 定义一个最简单的generator函数function* helloWorldGenerator() { yield 'hello'; yield 'world'; return 'ending';}// 获得指向内部状态的指针对象var hw = helloWorldGenerator();console.log(hw.next()); //{ value: 'hello', done: false }console.log(hw.next()); //{ value: 'world', done: false }console.log(hw.next()); //{ value: 'ending', done: true }console.log(hw.next()); //{ value: undefined, done: true }上面的例子执行过程如下:
a.遇到yield语句,就暂停执行后面的操作,并将紧跟在yield后面的那个表达式的值,作为返回的对象的value属性值。
b.下一次调用next方法时,再继续往下执行,直到遇到下一个yield语句。
c.如果没有再遇到新的yield语句,就一直运行到函数结束,直到return语句为止,并将return语句后面的表达式的值,作为返回的对象的value属性值。
d.如果该函数没有return语句,则返回的对象的value属性值为undefined。
4.yield语句有没有返回值?
二、 async 函数