SOURCE

const Thunk = function (fn) {
    return function (...args) {
        return function (callback) {
            return fn.call(this, ...args, callback)
        }
    }
}

// 基于Thunk函数的Genertor函数自动执行器
function run(fn) {
    let gen = fn()
    function next(err, data) {
        // 将指针移动到Generator函数的下一步
        let result = gen.next(data)
        // 判断是否结束
        if (result.done) return
        // 递归,把next放进.value中
        result.value(next)
    }
    next()
}

// 模拟异步方法
let sleep = function (n, callback) {
    setTimeout(() => {
        console.log(n)
        callback && callback(n)
    }, n)
}

// 模拟异步方法进行Thunk转换
let sleepThunk = Thunk(sleep)

// Generator函数
let gen = function* () {
    let f1 = yield sleepThunk(1000)
    let f2 = yield sleepThunk(1500)
    // ...
    let fn = yield sleepThunk(2000)
}

run(gen)
console 命令行工具 X clear

                    
>
console