聊一聊Promise、then、catch

216 阅读1分钟

Promise的基本用法

let promise = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve(1)
    },1000)
})
//1.通过then.catch链式调用 “成功、失败” 的写法
promise.then(res=>{console.log('成功回调',res)})
.catch(err=>{console.log('失败回调',err)})

//2.利用then第二个参数处理 “失败、回调” 的写法
promise.then(res=>{console.log('成功回调',res)},
err=>{console.log('失败回调',err)})

Promise可以通过 then 的方法来处理回调,then 有两个参数,第一个触发resolve(成功)的回调,第二个触发reject(失败)的回调。推荐使用catch写法来捕获异常

Promise原理

  1. Promise其实就是一个构造函数,我们调用他的时候,通过new Promise来创建一个实例,然后通过链式调用来处理
  2. new Promise是一个同步任务,Promisethen方法是一个微任务,在执行上下文的时候,promise是立即执行的,then 方法则是在执行完主线程后再执行。(这里涉及到Event loop

手写一个基础版的Promise

    class WPromise {
      static PENDING = "pengding";
      static FUFILLED = "fulfilled";
      static REJECTED = "rejected";
      constructor(executor) {
        this.status = WPromise.PENDING;
        this.value = null;
        executor(this._resolve.bind(this), this._reject.bind(this));
      }

      _resolve(value) {
        if (this.status === WPromise.PENDING) {
          this.status = WPromise.FUFILLED;
          this.value = value;
        }
      }

      _reject(reason) {
        if (this.status === WPromise.PENDING) {
          this.status = WPromise.REJECTED;
          this.value = reason;
        }
      }

      then(res, req) {
        if (this.status === WPromise.FUFILLED && res) {
          res(this.value);
        }
        if (this.status === WPromise.REJECTED && req) {
          req(this.value);
        }
      }
    }

    new WPromise((resolve, reject) => {
      resolve(5);
      resolve(6);
      reject(7);
    }).then(
      (res) => {
        console.log("成功", res);
      },
      (err) => {
        console.log("失败", err);
      }
    );