手写一个Promise

   class MyPromise {

      constructor(fn) {
        this.state = "open";
        this.result = null;
        this.callBack = [];
        // 绑定this,并接受参数 => bind
        fn(MyPromise.resolve.bind(this), MyPromise.reject.bind(this));
      }

      // 静态方法
      static resolve(params) {
        this.state = "success";
        this.result = params;
        this.callBack.forEach(item => {
          const { resFn, resolve } = item.success;
          resolve(resFn(this.result))
        });
      }

      // 静态方法
      static reject(params) {
        this.state = "full";
        this.result = params;
        this.callBack.forEach(item => {
          const { rejFn, reject } = item.full;
          reject(rejFn(this.result))
        });
      }

      then(resFn, rejFn) {

        const _this = this;
        
        // 返回的是promise, 同时将then返回值,作为下个then函数的接收值
        return new MyPromise(function (resolve, reject) {
          if (_this.state === 'open') {
            _this.callBack.push({
              success: {
                resFn,
                resolve
              },
              full: {
                rejFn,
                reject
              }
            });
          } else if (_this.state === 'success') {
            var d = resFn(_this.result);
            resolve(d);
          } else if (_this.state === 'full') {
            var d = rejFn(_this.result);
            reject(d);
          }
        });


        // if (this.state === 'open') {
        //   // new MyPromise内部异步操作,then函数先执行了
        //   // 这时候由于resolve, reject函数并未执行,resolve, reject函数执行的结果,并未绑定在this.result上
        //   // resFn, rejFn函数执行,时获取不到this.result上的结果
        //   this.callBack.push({
        //     success: resFn,
        //     full: rejFn
        //   });
        // } else if (this.state === 'success') {
        //   // new MyPromise内部同步操作,then函数先执行了
        //   resFn(this.result);
        // } else if (this.state === 'full') {
        //   // new MyPromise内部同步操作,then函数先执行了
        //   rejFn(this.result);
        // }

      }

    };


    const myP = new MyPromise(function (resolve, reject) {
      setTimeout(function () {
        resolve(26)
      }, 1000);
    });

    myP.then(function (res) {
      console.log(res);
      return 23;
    }).then(function (res) {
      console.log(res, '888');
    })

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PromiseJavaScript 中的一种异步编程解决方案,可以避免回调地狱,以下是手写一个 Promise 的代码示例: ``` class MyPromise { constructor(executor) { this.status = 'pending'; this.value = undefined; this.reason = undefined; this.onResolvedCallbacks = []; this.onRejectedCallbacks = []; const resolve = (value) => { if (this.status === 'pending') { this.status = 'fulfilled'; this.value = value; this.onResolvedCallbacks.forEach(fn => fn()); } }; const reject = (reason) => { if (this.status === 'pending') { this.status = 'rejected'; this.reason = reason; this.onRejectedCallbacks.forEach(fn => fn()); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value; onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }; const promise2 = new MyPromise((resolve, reject) => { if (this.status === 'fulfilled') { setTimeout(() => { try { const x = onFulfilled(this.value); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); } else if (this.status === 'rejected') { setTimeout(() => { try { const x = onRejected(this.reason); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); } else { this.onResolvedCallbacks.push(() => { setTimeout(() => { try { const x = onFulfilled(this.value); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); }); this.onRejectedCallbacks.push(() => { setTimeout(() => { try { const x = onRejected(this.reason); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); }); } }); return promise2; } resolvePromise(promise2, x, resolve, reject) { if (promise2 === x) { return reject(new TypeError('Chaining cycle detected for promise')); } let called = false; if (x !== null && (typeof x === 'object' || typeof x === 'function')) { try { const then = x.then; if (typeof then === 'function') { then.call(x, y => { if (called) return; called = true; this.resolvePromise(promise2, y, resolve, reject); }, r => { if (called) return; called = true; reject(r); }); } else { resolve(x); } } catch (error) { if (called) return; called = true; reject(error); } } else { resolve(x); } } catch(onRejected) { return this.then(null, onRejected); } finally(onFinally) { return this.then(

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值