手写一个简单的Promise

class  Promise {
     
     constructor(executorCallback) {
      let  _that = this;
      // 成功执行之后的返回值
      _that.value = ''; 
      //  失败的原因
      _that.reason = undefined;
      // 默认的状态
      _that.status = 'pending';

       // 成功执行的函数 
       // 成功执行会返回执行成功后的结果
      function resolve(value) {
          if ( _that.status === 'pending') {
            _that.status = 'fulfilled';
            _that.value = value;
          }
      }

      // 失败执行的函数
      // 失败返回失败的原因
       function reject(reason) {
        if ( _that.status === 'pending') {
            _that.reason = reason;
            _that.status = 'rejected';
        }
        
      }

      //  捕获异常
      try {
        executorCallback(resolve, reject);
      } catch (error) {
        reject(error)
      }

        
     }
 // then 的成功、失败 回调

 /*onfulfilled : 成功回调
  onRejected  : 失败回调
  */
 then(onFulfilled, onRejected) {
     if (_that.status === 'fulfilled') {
        onFulfilled(_that.value);
     }
     if (_that.status === 'rejected') {
        onRejected(_that.reason);
     }
 }

}


module.exports = Promise;
/* 
 * promise  初始化会立即执行
 * resolve 表示成功执行的函数
 * reject  表示失败执行的函数
 * 
 * promise  三个状态
 *  
 * pending: 初始状态,既不是成功,也不是失败状态。
   fulfilled: 意味着操作成功完成。
   rejected: 意味着操作失败。
 * 
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值