Skip to content

async await

  • S2017 标准引入了 async 函数。它就是 Generator 函数的语法糖。封装了Generator 函数函数的自动执行器。
  • await命令只能出现在 async 函数内部,否则都会报错。

原理

使用Generator函数封装async函数

所有的 async 函数都可以写成 fn 这种行式,spawn是函数就是自动执行器。

javascript
async function fn(args) {
 /** do something */
}

// 等同 

function fn(args) {
  return spawn(function* () {
    /** do something */
  });
}
async function fn(args) {
 /** do something */
}

// 等同 

function fn(args) {
  return spawn(function* () {
    /** do something */
  });
}

spawn 函数内部实现

javascript
function spawn(genF) {
  return new Promise(function(resolve, reject) {
    const gen = genF();
    function step(nextF) {
      let next;
      try {
        next = nextF();
      } catch(e) {
        return reject(e);
      }
      if(next.done) {
        return resolve(next.value);
      }
      Promise.resolve(next.value).then(function(v) {
        step(function() { return gen.next(v); });
      }, function(e) {
        step(function() { return gen.throw(e); });
      });
    }
    step(function() { return gen.next(undefined); });
  });
}
function spawn(genF) {
  return new Promise(function(resolve, reject) {
    const gen = genF();
    function step(nextF) {
      let next;
      try {
        next = nextF();
      } catch(e) {
        return reject(e);
      }
      if(next.done) {
        return resolve(next.value);
      }
      Promise.resolve(next.value).then(function(v) {
        step(function() { return gen.next(v); });
      }, function(e) {
        step(function() { return gen.throw(e); });
      });
    }
    step(function() { return gen.next(undefined); });
  });
}