promise A+ 第二遍

2022/5/5 23:43:33

本文主要是介绍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>

 



这篇关于promise A+ 第二遍的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程