##### 17.Generator 函数
> Generator 函数是 ES6 提供的一种异步编程解决方案
>
> Generator 函数是一个状态机,封装了多个内部状态。
>
> 执行 Generator 函数会返回一个遍历器对象,也就是说,Generator 函数除了状态机,还是一个遍历器对象生成函数。返回的遍历器对象,可以依次遍历 Generator 函数内部的每一个状态。
###### 17-1 基本语法
function *gen(){
console.log(1)
yield;
console.log(2)
yield;
console.log(3)
}
let g = gen()
g.next()
g.next()
g.next()
调用一次next 只打印1 只走console.log(1) 遇到yield就停了 要再往下走 再next
刚开始不写next没有任何结果
yield(产出)表达式是暂停执行的标记,而next方法可以恢复执行。
function *gen(){
yield 1;
yield 2;
}
let g = gen()
let res1 = g.next()
console.log(res1)
let res2 = g.next()
console.log(res2)
let res3 = g.next()
console.log(res3)
function *gen(){
let res1 = yield;
console.log(res1)
let res2 = yield;
console.log(res2)
}
let g = gen()
g.next("data-1")
g.next("data-2")
g.next("data-3")
```
###### 17-2 异步流程
**手动版本**
function *gen(){
let res1 = yield ajax("1.json")
console.log(res1)
let res2 = yield ajax("2.json")
console.log(res2)
}
let g = gen()
g.next().value.then(data=>{
g.next(data).value.then(data=>{
g.next(data)
})
})
**自动版本**
function* gen() {**自动版本**
let res1 = yield ajax("1.json")
console.log(res1)
let res2 = yield ajax("2.json")
console.log(res2)
}
function AutoRun(gen) {
let g = gen();
function next(data) {
let res = g.next(data);
if (res.done) return
res.value.then(function (data) {
next(data);
});
}
next();
}
AutoRun(gen);