promise实现
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
   |    function myPromise(cb) {       this.state = 'pending';        this.result = null;                     cb(this.resolve.bind(this), this.reject.bind(this));   };
    myPromise.prototype.resolve = function(val) {       if (this.state === 'pending') {           this.state = 'fullfiled';           this.result = val;       };   };
    myPromise.prototype.reject = function(val) {       if (this.state === 'pending') {           this.state = 'rejected';           this.result = val;       };   };
       myPromise.prototype.then = function(isResolved, isRejected) {       if (this.state === 'fullfiled') {           const res = isResolved(this.result);           if (res instanceof myPromise) {               return res;           };           return this;       } else if (this.state === 'rejected') {           const error = new TypeError(this.result);           const res = isRejected(error);           if (res instanceof myPromise && auguments[0]) {               return res;           }           return this;       }   };
       myPromise.prototype.catch = function(isRejected) {       if (this.state === 'rejected') {           const error = new TypeError(this.result);           const res = isRejected(error);           if (res instanceof myPromise && auguments[0]) {               return res;           }           return this;       }   }
    let promise = new myPromise((resolve, reject) => {       reject("哎呦出错了");   });
    promise       .then((data) => {           console.log(data);       }, (data) => {           console.log(data);       })
 
  |