手写Promise

编码1 / 2023-05-11 / 原文

//计录Promise的三种状态
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

//创建微队列,把传递的函数放到微队列
function runMicroTask(callback) {
  if(process && process.nextTick) {
    process.nextTick(callback); //将函数传递进来放到微队列,node环境
  } else if (MutationObserver) {
    //MutationObserver 浏览器微队列
    const p = document.createElement("p"); //创建p标签
    const observer = new MutationObserver(callback); //放入微队列
    observer.observe(p, {
      childList: true, //观察内部发送的变化
    });
    p.innerHTML = "1";
  } else {
    setTimeout(callback, 0); //等待0秒好执行
  }
}

//判断是不是promise
function isPromise(obj){
    return !!(
        obj && typeof obj === 'object'
        &&
        typeof obj.then === 'function')
}

class MyPromise1 {
  //构造一个执行器(execute)
  constructor(executor) {
    //需要执行的状态:
    this._state = PENDING;
    this._value = undefined;
    this._pushHandlers = [];//存放微队列的地方
    //执行器有两个参数,成功,失败
    executor(this._resolve.bind(this), this._reject.bind(this));
  }
  //更改任务状态
  _changeState(newState, value) {
    //添加if判断,只能发送第一个请求,后面请求不在执行
    if (this._state !== PENDING) {
      return;
    }
    this._state = newState;
    this._value = value;
    this._runHandlers();//重新执行
  }
  //创建一个函数,写入队列
  _pushHandler(executor,state,resolve,reject){
    this._pushHandlers.push({
        executor,
        state,
        resolve,
        reject
    })
  }
  //根据实际情况执行队列
  _runHandlers(){
    //当前函数还在挂起,则不执行
    if(this._state === PENDING){
        return
    }
    //每次执行完一个队列后,将队列删除
    while(this._pushHandlers[0]){
        const handler = this._pushHandlers[0]//将队列赋值
        this._runOneHandler(handler);//该函数操作该队列,操作完成后
        this._pushHandlers.shift()//删除已操作过的队列
    }
  }

  //处理一个handler
  _runOneHandler({executor,state,resolve,reject}){
    //进入微队列
    runMicroTask(()=>{
        //状态不一致,则不执行
        if(this._state !== state){
            return;
        }
        //当函数名称不等于function
        if(typeof executor !== 'function'){
            //则将前一个的值给后面
            this._state === FULFILLED ? resolve(this._value) : reject(this._value)
            return;
        }
        try {
            //取出executor里面的值
            const relute = executor(this._value);
            if(isPromise(relute)){
                //isPromise判断是不是Promist如果是,带着relute的值,看看是那个状态,将值给对应的resolve/reject
                resolve.then(resolve,reject)
            }else{
                resolve(relute)//其他情况的话,直接输出该属性
            }
        } catch (error) {
            reject(error)//如果错误,则打印错误
        }
    })
  }

  //成功的方法
  _resolve(data) {
    this._changeState(FULFILLED, data);
  }

  //失败的方法
  _reject(fail) {
    this._changeState(REJECTED, fail);
  }

  //有状态后,肯定有then函数,then函数有两个参数,一个成功(onFulfilled),一个失败(onRejected)
  then(onFulfilled, onRejected) {
    return new MyPromise1((resolve, reject) => {
        this._pushHandler(onFulfilled,FULFILLED,resolve,reject);//成功的
        this._pushHandler(onRejected,REJECTED,resolve,reject);//失败的
        this._runHandlers();//重新执行
    });
  }
}



const pro = new MyPromise1((resolve, reject) => {
   setTimeout(()=>{
    resolve(1)
   })
});
const pro2 = pro.then((data)=>{
    console.log(data)
  // throw 'abc';
    return 123;
})
setTimeout(()=>{
    console.log(pro2)
},1000)
//const pro1 = pro.then(function A(){})
// setTimeout(()=>{
//     console.log(pro)
//     console.log(pro1)
// },1500)
// pro.then(
//     function A2(){},
//     function B2(){}
// )
//console.log(pro)  
//pro.then(function B1(){},function B2(){})
//console.log(pro)