Generator函数自执行

Generator函数实现


function* gen(x){
    var y = yield x + 2;
    return y
}

//1.调用g函数会返回一个内部的指针
var g = gen(1);

//2.每次调用next会返回一个对象,{value,done}表示当前阶段的信息
g.next()//{value:3,done:false}
//3.如果第二次调用next方法,传入了参数则会作为上一阶段next的返回结果
g.next(2)//{value:2,done:true}

自动执行generator函数

let i = 0
function getNumber(){
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve(++i)
        },1000)
    })
}

function *read(){
    let a = yield getNumber();
    console.log(a)
    let b = yield 'b'
    console.log(b)
    let c = yield getNumber();
    console.log(c)
}

function co(gen){
    return new Promise((resolve, reject) => {
        let g = gen()
        function next(lastValue){
            let { value, done } = g.next(lastValue)
            if(done){
                resolve(lastValue)
            } else {
                if(value instanceof Promise){
                    value.then(next,err => reject(err))
                } else {
                     next(value)
                }
            }
        }
        next()
    })
}
co(read).then((data) => {
    console.log(data)
},(reason) => {
    console.log(reason)
})
posted @ 2019-03-21 16:25  pluscat  阅读(509)  评论(0编辑  收藏  举报