# 手写 CO执行器


function sleep(sec) {
  return new Promise(function (done) {
    setTimeout(() => done(sec), sec)
  });
}

co(function * () {
  let res = yield sleep(1000);
  console.log('over', res)
});



function co(gen) {
  let ctx = this;
  return new Promise((resolve, reject) => {
    if (typeof gen === 'function') gen = gen.apply(ctx);
    if (!gen || typeof gen.next !== 'function') return resolve(gen);

    run();

    function run(res) {
      let ret;
      try {
        ret = gen.next(res);
      } catch (e) {
        return reject(e);
      }
      next(ret);
    }

    function next(ret) {
      if (ret.done) return resolve(ret.value);
      let promise = ret.value;
      if (promise && typeof promise.then === 'function') {
        return promise.then(run);
      }

      reject('You may yield a Promise');
    }
  });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43