promise A+ 第二遍

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>promise A+ 规范</title>
  </head>
  <body>
    <script>
      let a = `onFulfilled,onRejected 不会立马调用,而是被留存下来,留存到整个promise 进入已决状态,根据状态的区分而进行调用,所以这里不能用一个变量
               而是用一个数组 then是可以绑定多次的,  `;
      const PENDING = 'pending';
      const FULFILLED = 'fulfilled';
      const REJECTED = 'rejected';
      class myPromise {
        constructor(executor) {
          this.status = PENDING;
          this.data = null;
          this.reason = null;
          this.dispatchers = [];
          try {
            executor(this.__resolve.bind(this), this.__reject.bind(this));
          } catch (err) {
            this.__reject(err);
          }
        }
        __resolve(data) {
          this.__updateStatus(FULFILLED);
          this.data = data;
          this.__executeDispatchers();
        }
        __reject(reason) {
          this.__updateStatus(REJECTED);
          this.reason = reason;
          this.__executeDispatchers();
        }
        then(onFulfilled, onRejected) {
          return new myPromise((resolve, reject) => {
            this.dispatchers.push(
              {
                status: FULFILLED,
                dispatcher: onFulfilled,
                resolve,
                reject
              },
              {
                status: REJECTED,
                dispatcher: onRejected,
                resolve,
                reject
              }
            );
          });
        }
        catch(onRejected) {
          this.then(null, onRejected);
        }
        __updateStatus(newStatus) {
          if (this.status !== PENDING) return;
          this.status = newStatus;
        }
        __executeDispatchers() {
          if (this.status === PENDING) return;
          for (const dispatcherConf of this.dispatchers) {
            this.__executeDispatcher(dispatcherConf);
          }
        }
        __executeDispatcher({ status, dispatcher, resolve, reject }) {
          if (this.status !== status) return;
          if (typeof dispatcher !== 'function') {
            this.status === FULFILLED ? resolve(this.data) : reject(this.data);
          }
          try {
            const result = dispatcher(this.status === FULFILLED ? this.data : this.reason);
            resolve(result);
          } catch (err) {
            reject(err);
          }
        }
      }

      const myPro = new myPromise((resolve, reject) => {
        setTimeout(() => {
          resolve(11);
        }, 1000);
      });
      myPro.then(r => {
        console.log(r);
      });
    </script>
  </body>
</html>

 

posted @ 2022-05-05 23:21  苹果π  阅读(13)  评论(0编辑  收藏  举报