Generator 快速理解

  你理解的 Generator 是什么?  

  Generator 算是 ES6 中难理解的概念之⼀了,Generator 最⼤的 特点就是可以控制函数的执⾏。在这⼀⼩节中我们不会去讲什么是 Generator,⽽是把重点放在 Generator 的⼀些容易困惑的地 ⽅。

  直接调用一个generator和调用函数不一样,foo(5)仅仅是创建了一个generator对象,还没有去执行它。

  调用generator对象有两个方法,一是不断地调用generator对象的next()方法:

function* foo(x) {
    let y = 2 * (yield(x + 1)) 
    let z = yield(y / 3) 
    return (x + y + z)
}
let it = foo(5) 
console.log(it.next()) // => {value: 6, done: false} 
console.log(it.next(12)) // => {value: 8, done: false} 
console.log(it.next(13)) // => {value: 42, done: true}

  你也许会疑惑为什么会产⽣与你预想不同的值,接下来就让我为你逐 ⾏代码分析原因 

  • ⾸先 Generator 函数调⽤和普通函数不同,它会返回⼀个迭 代器
  • 当执⾏第⼀次 next 时,传参会被忽略,并且函数暂停在 yield (x + 1) 处,所以返回 5 + 1 = 6
  • 当执⾏第⼆次 next 时,传⼊的参数等于上⼀个 yield 的返 回值,如果你不传参,yield 永远返回 undefined。此时 let y = 2 * 12,所以第⼆个 yield 等于 2 * 12 / 3 = 8
  • 当执⾏第三次 next 时,传⼊的参数会传递给 z,所以 z = 13, x = 5, y = 24,相加等于 42

  Generator 函数⼀般⻅到的不多,其实也于他有点绕有关系,并且 ⼀般会配合 co 库去使⽤。当然,我们可以通过 Generator 函数解 决回调地狱的问题,可以把之前的回调地狱例⼦改写为如下代码: 

function* fetch() {
    yield ajax(url, () => {});
    yield ajax(url1, () => {});
    yield ajax(url2, () => {});
}
let it = fetch() 
let result1 = it.next() 
let result2 = it.next() 
let result3 = it.next()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值