function * gen () { yield 'hello' yield* 'world' yield fn() // fn()必须返回iterable的内容. return 'ending' }
generator方法返回的是Iterator接口。异步
function* fib(max) { let index = 0 let [prev, cur] = [0, 1]; while (index < max) { (yield(cur)); [prev, cur] = [cur, cur + prev] index++ } } console.log([...fib(15)]) // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 ]
generator函数的实例只有执行next()
方法才执行下一段。不然就不执行。正因其有此特性,才能够执行一段后执行其它代码而后再执行下一段。函数
function * toggle (init) { while (true) { yield init init = !init } } let g = toggle(false) g.next() // { value: false, done: false } // other code g.next() // { value: true, done: false } // other code g.next() // { value: false, done: false } // other code g.next() // { value: true, done: false }
function * readFile () { var r0 = yield fetch('url0') // fetch是异步读取文件的方法 var r1 = yield fetch('url1') var r2 = yield fetch('url2') }
因generator方法的实例不会自动执行,须要使用next()
方法才能执行。在此例中咱们但愿该实例能够自动执行完函数体。如今咱们须要一个让generator实例自动执行的方法(自执行方法)。这里介绍一个co
模块。fetch
co(readFile())