简单实现一个promise

promise就是一个对象,用来传递异步操作的消息。

首先了解一下 promise的用法

const promise = new Promise((resolve, reject) => {
   setTimeout(() => {
       resolve("success");
   });
});
promise.then(
	value => {
	 console.log(value) 
	}, 
 	reason => { 
	 console.log(reason) 
	}
 );

完成一个promise首先一个Promise构造函数,Promise 的构造函数接收了一个回调函数,这个回调执行器(executor),executor 里面的 resolve, reject 也是两个函数,负责改变 Promise 实例的状态和它的值,then 函数中的回调在状态改变后执行,除此之外 then 还支持链式调用。

class MyPromise {
    constructor(executor){
        // 校验executor
        if(typeof executor !== "function"){
            throw new Error('ERROR');
        };

        this.value = undefined; //终值=>resolve的值
        this.reason = undefined;//拒因=>reject的值
        this.state = "pending";//状态

        this.onFulfilledCallbacks = [];// 成功回调
        this.onRejectedCallbacks = [];// 失败回调

        const resolve = (value)=>{
            // 成功后的一系列操作(状态的改变,成功回调的执行)
            if(this.state === "pending"){
                this.state = "fulfilled";
                this.value = value;
                this.onFulfilledCallbacks.forEach(fn=>fn(this.value));
            };
        };
        const reject = (reason)=>{
            // 失败后的一系列操作(状态的改变,成功回调的执行)
            if(this.state === "pending"){
                this.state = "rejected";
                this.reason = reason;
                this.onRejectedCallbacks.forEach(fn=>fn(this.reason));
            }
        };
        try{
            executor(resolve,reject);
        }catch(err){
            reject(err);
        }
    }
    then(onFulfilled,onRejected){

        // onFulfilled未传值或传的值不是function的时候
        // 自动把onFulfilled变成一个函数
        if(typeof onFulfilled !== "function"){
            onFulfilled = value => value;
        };

        //onRejected未传值或传的值不是function的时候
        //自动把onFulfilled变成一个函数,并抛出错误
        if(typeof onRejected !== "function"){
            onRejected =  reason => { throw reason }
        };

        if(this.state === "pending"){
            this.onFulfilledCallbacks.push(
                (value)=>{
                    setTimeout(()=>onFulfilled(value))
                }
            );
            this.onRejectedCallbacks.push(
                (reason)=>{
                    setTimeout(()=>onRejected(reason))
                }
            );
        };
        if(this.state === "fulfilled"){
            setTimeout(()=>onFulfilled(this.value));
        };

        if(this.state === "rejected"){
            setTimeout(()=>onRejected(this.reason));
        };
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值