• ES6知识点整理之----async----实现原理以及与其他异步的比较


    async 函数的实现原理,就是将 Generator 函数和自动执行器,包装在一个函数里。

    async function fn(args) {
      // ...
    }
    
    // 等同于
    
    function fn(args) {
      return spawn(function* () {
        // ...
      });
    }
    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); });
      });
    }

    与其他异步处理方法的比较

    //Promise
    function chainAnimationsPromise(elem, animations) {
    
      // 变量ret用来保存上一个动画的返回值
      let ret = null;
    
      // 新建一个空的Promise
      let p = Promise.resolve();
    
      // 使用then方法,添加所有动画
      for(let anim of animations) {
        p = p.then(function(val) {
          ret = val;
          return anim(elem);
        });
      }
    
      // 返回一个部署了错误捕捉机制的Promise
      return p.catch(function(e) {
        /* 忽略错误,继续执行 */
      }).then(function() {
        return ret;
      });
    
    }
    //Generator
    function chainAnimationsGenerator(elem, animations) {
    
      return spawn(function*() {
        let ret = null;
        try {
          for(let anim of animations) {
            ret = yield anim(elem);
          }
        } catch(e) {
          /* 忽略错误,继续执行 */
        }
        return ret;
      });
    
    }
    //async
    async function chainAnimationsAsync(elem, animations) {
      let ret = null;
      try {
        for(let anim of animations) {
          ret = await anim(elem);
        }
      } catch(e) {
        /* 忽略错误,继续执行 */
      }
      return ret;
    }
  • 相关阅读:
    HDOJ2553 N皇后问题
    NYOJ284 坦克大战 BFS/优先队列
    NYOJ14 会场安排问题 贪心
    POJ1664 放苹果
    NYOJ119 士兵杀敌(三) RMQ
    POJ3264 Balanced Lineup RMQ/线段树
    POJ1127 Jack Straws
    HDOJ1128 Self Numbers
    水晶报表CrystalReports很强大也很简单!
    PetShop项目学习笔记(三)
  • 原文地址:https://www.cnblogs.com/adhehe/p/9684751.html
Copyright © 2020-2023  润新知