十一、等待者模式

2022-06-11 09:33:08 浏览数 (1)

十一、等待者模式

通过对多个异步进程的监听,对未来事件进行统一管理

代码语言:javascript复制
1、等待者模式例子
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script>
    
    /*

    waiter.when(异步事件1, 异步事件2, ...).done(fn).fail(fn)    
        
    */

    //等待者模式
    // 成熟的等待者模式 有 async/await 模式 和 promise模式
    function Waiter() { 
      var dfd = []; // 用来存放异步事件
      var doneArray = []; // 用来存放done注册成功之后的回调
      var failArray = []; // 存放失败的回调
      this.when = function () { 
        // 获取arguments -> 一个类数组对象
        dfd = Array.prototype.slice.call(arguments); // 将类数组转换成数组
        for (var i = dfd.length -1; i >= 0; i--) {
          var d = dfd[i];
          if (!d || d.rejected || d.resolved || !(d instanceof Defer)) {
            dfd.splice(i, 1);
          }
        }
        return this
      }
      this.done = function () { 
        var args = Array.prototype.slice.call(arguments);
        doneArray = doneArray.concat(args)
        return this
      }
      this.fail = function () {  
        var args = Array.prototype.slice.call(arguments);
        failArray = failArray.concat(args)
        return this
      }
      this.Defered = function () {  
        return new Defer()
      }
      var Defer = function () { 
        this.resolved = false;
        this.rejected = false;
      }
      Defer.prototype = {
        resolve: function () { 
          this.resolved = true;
          for (var i = 0; i < dfd.length; i  ) {
            if (!dfd[i].resolved) {
              return
            }
          }
          // 如果全部完成,就不会被return出去,则可执行下面的语句
          // 执行成功的回调函数
          _exec(doneArray)
        },
        reject: function () { 
          this.rejected = true;
          // 执行失败的回调
          _exec(failArray)
        }
      }
      function _exec(arr) { 
        for( var i = 0; i < arr.length; i  ) {
          arr[i] && arr[i]()
        }
       }
    }

    var waiter = new Waiter()

    var async1 = function () { 
        var dfd = waiter.Defered()
        setTimeout(function () { 
            console.log('async1 done');
            dfd.resolve()
        }, 1000)
        return dfd
    }
    var async2 = function () { 
        var dfd = waiter.Defered()
        setTimeout(function () { 
            console.log('async1 done');
            dfd.resolve()
        }, 2000)
        return dfd
    }

    waiter.when(async1(), async2()).done(function () { 
        console.log('success');
    }).fail(function () { 
        console.log('fail');
    })

    </script>
</head>
<body>
    
</body>
</html>

0 人点赞