手写Promise A+规范中的Promise

Promise

需要明白的知识:

	1、this 指向,在一个函数中this指向取决于这个函数的调用方式
	2、私有属性, 命名规范内部属性可以是在前面加下划线_  ,新出的私有属性是加# 如 #state
	3、 Promise状态一旦确定后就无法改变,三个状态 pending准备、fulfilled成功、rejected失败
	4、硬编码 hard code 难以维护,可通过常量来代替硬编码

第一步Promise构造器的实现

  // 定义常量
  const PENDING = 'pending';
  const FULFILLED = 'fulfilled';
  const REJECTED = 'rejected';
 // 定义一个类
 class myPromise {
	#state = PENDING;
	#result = undefined;
	constructor(executor){
		const resolve = (data)=> {
			this.#changeState(data,FULFILLED);
		};
		const reject = (data)=> {
			this.#changeState(data,REJECTED);
		};
		try{
 			executor(resolve,reject);
		}catch(e) {
			reject(e);
		}
    }
    #changeState(data,state){
		if(this.#state !== PENDING) return; //这个作用就是当promise状态一旦改变就不在改变
			this.#state = state;
			this.#result = data;
    }
 }

需要明白的知识:

	1、then方法返回的是一个Promise
	2、then方法中两个参数,什么时候执行第一个参数,什么时候执行第二个参数:   
	参数三种情况:是函数、不是函数、是Promise
	3、then方法中是如何去解决pending状态,也就是延时改变Promise的状态
	4、then方法中返回的Promise中,resolve和reject的执行

第二步Promise的then方法实现

	// 定义常量
  const PENDING = 'pending';
  const FULFILLED = 'fulfilled';
  const REJECTED = 'rejected';
 // 定义一个类
 class myPromise {
	#state = PENDING;
	#result = undefined;
	#handlers = [];
	constructor(executor){
		const resolve = (data)=> {
			this.#changeState(data,FULFILLED);
		};
		const reject = (data)=> {
			this.#changeState(data,REJECTED);
		};
		try{
 			executor(resolve,reject);
		}catch(e) {
			reject(e);
		}
    }
    #changeState(data,state){
		if(this.#state !== PENDING) return; //这个作用就是当promise状态一旦改变就不在改变
			this.#state = state;
			this.#result = data;
			this.#run();
    }
    #isPromiseLike(value) { // 判断是否为promise,需满足promise A+规范,最重要的是需要then函数
		if(value !== null && (typeof value === 'object' || typeof value === 'function')) {
			return typeof value.then === 'function';
		}
		return false;
	}
	   #runMicroTask (func) {
        if(typeof process === 'object' && typeof process.nextTick === 'function') {
            process.nextTick(func); // node 环境
        }else if(typeof MutationObserver === 'function') {
            const ob = new MutationObserver(func); 
            //浏览器环境,该观察器在观察某一元素是否发生变化,只要发生变化了就会把func函数放在微队列中执行
            const textNode = document.createTextNode('1');
            ob.observe(textNode, {characterData: true}); //观察字符的变化
            textNode.data = '2';

        }
    }
    #runOne (callback,resolve,reject){
		this.#runMicroTask(()=> {
			if(typeof callback !== 'function') {
			const settled = this.#state === FUIFILLED?reslove:reject;
			settled(this.#result);
			return;
		}else {
		    try{
				    const data = onFulfilled(this.#result);
				    if(this.#isPromiseLike(data)) {
						data.then(resolve,reject);
					}else{
						resolve(data);
					}
			   }catch(e){
					reject(e);
			   }
		});
	}
    #run(){
    	if(this.#state === PENDING) return;
		while(this.#handlers.length>0){
			const {onFulfilled,onRejected,resolve,reject} = this.#handlers.unshift();
			if(this.#state === FULFILLED) {
				this.#runOne(onFulfilled,resolve,reject);
			}else {
				this.#runOne(onRejected,resolce,reject);
			}
		}
	}
    then(onFulfilled,onRejected) {
		return new myPromise((resolve, reject) => {
			this.#handlers.push({onFulfilled,onRejected,resolve,reject});
			this.#run();
		});
	}
 }

第三步是否为Promise以及微队列方法实现

	  #isPromiseLike(value) { // 判断是否为promise,需满足promise A+规范,最重要的是需要then函数
		if(value !== null && (typeof value === 'object' || typeof value === 'function')) {
			return typeof value.then === 'function';
		}
		return false;
	}
	   #runMicroTask (func) {
        if(typeof process === 'object' && typeof process.nextTick === 'function') {
            process.nextTick(func); // node 环境
        }else if(typeof MutationObserver === 'function') {
            const ob = new MutationObserver(func); 
            //浏览器环境,该观察器在观察某一元素是否发生变化,只要发生变化了就会把func函数放在微队列中执行
            const textNode = document.createTextNode('1');
            ob.observe(textNode, {characterData: true}); //观察字符的变化
            textNode.data = '2';

        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值