该函数的特点:执行过程中可以进行暂停,然后可以继续接着暂停的状态继续
基本使用
function* foo() {for (let i = 0; i < 3; i++) {yield i}}let f = foo()console.log(f.next())console.log(f.next())console.log(f.next())console.log(f.next())

这里打印输出的结果就是迭代器对象
错误示范
yield 这个关键字只能在 generator 生成器函数中使用
function* gen(args) {
args.forEach(item => {
yield item + 1
})
}

这里的报错原因就是,yield 在 forEach() 函数中使用了,而不是直接在generator 函数中使用。
next的参数
function* gen(x) {
let y = 2 + (yield(x + 1));
let z = yield(y / 3)
return x + y + z
}
let g = gen(5)
console.log(g.next()) // 6
console.log(g.next()) // NaN
console.log(g.next()) // NaN

这里的NaN 出现的原因是,后面两个next() 中没有传参
console.log(g.next())
console.log(g.next(12))
console.log(g.next(13))
获取7或7的倍数
function* count(x = 1) {
while (true) {
if (x % 7 === 0) {
yield x
}
x++
}
}
let n = count()
console.log(n.next().value) // 7
console.log(n.next().value) // 14
console.log(n.next().value) // 21
console.log(n.next().value) // 28
利用生成器进行异步请求
function ajax(url, cb) {
return cb()
}
function request(url) {
ajax(url, res => {
getData.next(res)
})
}
function* gen() {
let res1 = yield request('static/a.json')
console.log(res1)
let res2 = yield request('static/b.json')
console.log(res2)
let res3 = yield request('static/c.json')
console.log(res3)
}
let getData = gen()
getData.next()

