generator 是一种语法糖 每个函数需要用 ‘*’ 来标识 (生成器)
function* generator () {
const list = [1, 2, 3]
for (let i of list) {
yield i
}
}
let g = generator()
console.log(g.next())
console.log(g.next())
console.log(g.next())
console.log(g.next())
async
function longTimeFn(time) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(time)
}, time)
})
}
function asyncFun (generator) {
const iterator = generator()
const next = (data) => {
const {
value,
done
} = iterator.next(data)
if (done) {
return
}
value.then(data => {
next(data)
})
}
next()
}
asyncFun(function* () {
let data = yield longTimeFn(1000)
console.log(data)
data = yield longTimeFn(2000)
console.log(data)
return data
})