Promise个人理解


之前就想整理一篇关于promise的个人理解,终于可以静下心来记录一下。
在我们学习一样东西的时候通常是从what-why-how这

什么是promise对象

promise对象表示了一个异步操作的状态结果

为什么会用到promise

经常,我们会在需要同步化代码的时候,解决回调地狱的时候使用到promise
所以,使用promise可以解决回调地狱的问题,帮助我们的代码更加美观

怎么使用promise

一个简单的使用

  let promise1 = new Promise((resolve, reject) => {
            setTimeout(() => { resolve(100); }, 1000);
        });
        promise1.then(rst => {
            console.log(rst);
        });

解释下:这里的定时器是一个异步操作,在一秒后,进入成功回调参数为100,也就是下面的rst的值。在这个promise进入成功或者失败回调后,打印rst的值(100)。

到这里为止,应该就会使用promise了。
即使这样,下面的知识点也是非常重要的。

promise的状态

一个promise对象某时刻一定是处于这三种状态中的一种:pending(待定), fulfilled(成功), or rejected(失败).
在状态改为fulfilled/rejected之前,这个promise一直处于pending状态,一旦状态改为fulfilled/rejected后这个promise的状态就不能再改变了

promise的then,catch,finally方法

then、catch、finally这三个方法是promise的原型方法,使用这三个方法就可以完成一个完整的一个链式调用。

var p1 = new Promise(function(resolve, reject) {
  resolve('Success');
});

p1.then(function(value) {
  console.log(value); // "Success!"
  return Promise.reject('oh, no!');
}).catch(function(e) {
  console.log(e); // "oh, no!"
}).then(function(){
  console.log('after a catch the chain is restored');
}, function () {
  console.log('Not fired due to the catch');
});

then和catch对比
catch只处理拒绝情况下的回调,他的情况和Promise.prototype.then(undefined, onRejected)相同。
then既可以处理成功也可以处理拒绝情况(接受两个回调)。

之所以then、catch可以进行链式调用,是因为他们返回的都是promise对象

手写一个promise

class MyPromise {
  constructor(fn) {
    this.resolvedCallBack = [];
    this.rejectedCallBack = [];

    this.status = 'PEDDING';
    this.value = '';
    fn(this.resolve.bind(this), this.reject.bind(this));
  }
  resolve(value) {
    if (this.status === 'PEDDING') {
      this.status = 'RESOLVED';
      this.value = value;
      this.resolvedCallBack.map(cb => cb(value));
    }
  }
  reject(value) {
    if (this.state === 'PEDDING') {
      this.status = 'REJECTED';
      this.value = value;
      this.rejectedCallBack.map(cb => cb(value));
    }
  }
  then(onFulfilled, onRejected) {
    if (this.state === 'PEDDING') {
      this.resolvedCallBack(onFulfilled);
      this.rejectedCallBack(onRejected);
    }
    if (this.state === 'RESOLVED') {
      onFulfilled(this.value);
      onRejected(this.value);
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值