编辑代码

// 使用generator实现一个async/await的操作
console.log('使用generator实现一个async/await的操作')
function fn(num) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(num * 2)
        }, 1000)
    })
}

function* gen() {
   const num1 =  yield fn(1);
   const num2 =  yield fn(num1);
   const num3 =  yield fn(num2);
   return num3
}

// 使用高阶函数实现async返回promise
/**
 * 传入参数是一个generator的方法
 */
function generatorAsync(generatorFn) {
    return function () {
        return new Promise((resolve, reject) => {
            const g = generatorFn()
            const next1 = g.next()
            next1.value.then((res1) => {
                const next2 = g.next(res1)
                next2.value.then((res2) => {
                    const next3 = g.next(res2)
                    next3.value.then((res3) => {
                        resolve(g.next(res3).value)
                    })
                })
            })
        })
    }
}

const asyncFn = generatorAsync(gen)
asyncFn().then((res) => {
    console.log(res)
})