自执行的Generator 函数(async)

361 阅读1分钟

Generator 函数的 yield thunk 函数,可以实现自动执行的异步Generator(实现async),

//将普通方法转成thunk方法
function thunk(fn) {
  return function (...arg) {
    return function (cb) {
      arg.push(cb)
      fn.apply(this, arg)
    }
  }
}
function fn1(a, cb) {
  // body
  setTimeout(() => {
    cb(a)
  }, 1)

}
function fn2(a, cb) {
  // body
  setTimeout(() => {
    cb(a)
  }, 1)
}
const fn11 = thunk(fn1)
const fn22 = thunk(fn2)
console.log(fn11)

function* gen () {
  // body
  let a = yield fn11(1)
  let b = yield fn22(2)
}

//thunk的自动执行
function run (fn) {
  const g = fn()
  function step(data){
    const res = g.next(data)
    if(res.done)return res.value
    res.value(step)
    // res.value
  }
  step()
}
promise的自动执行
function run2(fn){
  const g = fn()
  function step(data){
    const res = g.next(data);
    if (res.done) return res.value;
    res.value.then(function(data){
      step(data);
    });
  }

  step();
}
run(gen)