LOADING

MiniKano的小窝


 

使用生成器实现async、await

使用递归执行Promise

// 生成器实现async await
const getData = (data = 0) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(1 + data)
        }, 1000);
    })
}

function* dataGen(data) {
    const res1 = yield getData(data)
    const res2 = yield getData(res1)
    const res3 = yield getData(res2)
    const res4 = yield getData(res3)
    console.log(res4);
}

const execGen = (fn) => {
    const genFn = fn()
    function run(data) {
        const res = genFn.next(data)
        if (res.done) return
        res.value.then((data) => {
            run(data)
        })
    }
    run()
}

const initVal = 100
execGen(()=>dataGen(initVal)) //104

execGen是核心代码,负责自动化Promise的then
dataGen 看着是不是有点眼熟?没错,这就是async与await的前身 :tushe:

async function dataGen(data) {
    const res1 = await getData(data)
    const res2 = await getData(res1)
    const res3 = await getData(res2)
    const res4 = await getData(res3)
    console.log(res4);
}
dataGen(100) //104
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注