一 、函数的定义
1、Generator 函数是一个普通函数。它不同于普通函数,是可以暂停执行的,所以函数名之前要加星号,以示区别。
2、整个Generator函数就是一个封装的异步任务,或者说是异步任务的容器,异步操作需要暂停的地方,都用yield语句。
二、什么是Generator函数
1、function 关键字和函数之间有一个星号(*),且内部使用yield表达式定义不同的内部状态。
2、调用Generator函数后,该函数并不执行,返回的也不是函数运行结果,而是一个指向内部状态的指针对象。
function fn(){ // 定义一个Generator函数
yield ‘hello’;
yield ‘world’;
return ‘end’;
}
var f1 =fn(); // 调用Generator函数
console.log(f1); // fn {[[GeneratorStatus]]: “suspended”}
console.log(f1.next()); // {value: “hello”, done: false}
console.log(f1.next()); // {value: “world”, done: false}
console.log(f1.next()); // {value: “end”, done: true}
console.log(f1.next()); // {value: undefined, done: true}