教你手写Promise

//定义三种状态
const success = 'success'
const pending = 'pending'
const fail = 'fail'

//定义用来实现的类
class Promise {
    //定义构造器用来初始化变量或方法
    constructor(execute) {
        //初始化状态
        this.status = pending
        //初始化值
        this.value = ''
        //初始化成功回调数组
        this.onsuccessCallback = []
        //初始化成功回调数组
        this.onfailCallback = []
        //初始化失败原因 
        this.reason = ''
        const resolve = (result) => {
            if (this.status == 'pending') {
                //改变状态
                this.status = success
                //赋值
                this.value = result
                //遍历并注册成功回调
                this.onsuccessCallback.forEach(fn => { fn() })
            }
        }
        const reject = (reason) => {
            if (this.status == 'pending') {
                //改变状态
                this.status = fail
                //赋值
                this.reason = reason
                //遍历并注册失败回调并传入原因
                this.onfailCallback.forEach(fn => { fn(this.reason) })
            }
        }

        //执行execute
        execute(resolve, reject)

    }
    //注册成功回调和失败回调以处理 Promise 的结果
    then(onResolved, onRejected) {
        const handle = (resolve, reject, callback) => {
            setTimeout(() => {
                try {
                    const result = callback(this.value)
                    if (result instanceof Promise) {
                        result.then(resolve, reject)
                    } else {
                        resolve(result)
                    }
                } catch (error) {
                    reject(error)
                }
            })
        }
        //返回一个新的 Promise,这使得可以创建 Promise 链。
        //如果成功或失败回调返回的是一个 Promise,我们等待该 Promise 解决,并根据其状态触发新的 Promise。
        return new Promise((resolve, reject) => {
            if (this.status == 'success') {
                handle(resolve, reject, onResolved)
            }
            if (this.status == 'fail') {
                handle(resolve, reject, onRejected)
            }
            //处理异步
            if (this.status == 'pending') {
                this.onsuccessCallback.push((value) => {
                    handle(resolve, reject, onResolved);
                });
                this.onfailCallback.push((reason) => {
                    handle(resolve, reject, onRejected);
                });
            }
        })

    }
    catch(onRejected) {
        return this.then(null, onRejected)
    }
    finally(onFinally) {
        return this.then(
            (value) => {
                onFinally();
                return value;
            },
            (reason) => {
                onFinally();
                throw reason;
            }
        );
    }
}


const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject('msg : hello' + '\n')
    }, 1000)

})
promise.then(result => {
    console.log('success' + '\n', result);
}, reject => {
    throw new Error(reject)
}).catch((error) => {
    console.log('error', error);
}).finally(() => {
    console.log('Finally executed');
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值