手写Promise 封装Promise resolve reject then catch Promise.resolve Promise.reject

Promsie 代码

(function (window) { //首先写一个自调用函数
    const PENDING = 'pending'
    const onREJECT = 'onReject'
    const onRESOLVE = 'onResolve'

    function Promise(executor) {
        this.status = PENDING // 存状态
        this.data = undefined // 存储结果值
        this.callbacks = [] // 存储回调函数
        const _this = this // 这个this 指向Promise 

        function resolve(value) { // 可以用箭头函数

            if (_this.status != PENDING) {
                // 状态只能有一次 不是pending直接结束
                return
            }
            _this.status = onRESOLVE //状态
            _this.data = value // 传过来的 value
            if (_this.callbacks.length > 0) { // 有函数就执行
                setTimeout(() => {
                    _this.callbacks.forEach(element => {
                        element.resolve(value)
                    });
                })
            }
        }

        function reject(reason) {
            if (_this.status != PENDING) {
                // 状态只能有一次 不是pending直接结束
                return
            }
            _this.status = onREJECT //状态
            _this.data = reason // 传过来的 value
            if (_this.callbacks.length > 0) { // 有函数就执行
                setTimeout(() => {
                    _this.callbacks.forEach(element => {
                        element.reject(reason)
                    });
                })
            }
        }

        try {
            executor(resolve, reject)
        } catch (error) { // 如果promise 有异常就变成reject
            reject(error)
        }

    } // promise 的 resolve 和 reject 

    Promise.prototype.then = function (resolve, reject) {
        resolve = typeof resolve === 'function' ? resolve : value => value //向后传成功的value
        reject = typeof reject === 'function' ? reject : reason => {
            throw reason
        } // 指定默认的失败回调(实现错误/异常传透关键点) 
        const self = this


        return new Promise((resolves, rejects) => {



            function handle(callBack) {
                // 1、如果抛出异常,return 的promise 就会失败 ,reason 就是 error
                // 2、如果回调函数返回的不是promise,return 的promise 就会成功,value 就是返回的值
                // 3、如果回调函数返回的是promise return 的promise 结果就是这个promise 的结果
                try {
                    const result = callBack(self.data)
                    // 捕获错误
                    if (result instanceof Promise) {
                        result.then(
                            value => {
                                resolves(value) // 当result 成功的时候 让return 的promise 也成功
                            },
                            reason => {
                                rejects(reason) // 当result 失败的时候 让return 的promise 也失败
                            }
                        )

                        // result.then(value, reason) // 简写

                    } else {
                        // 若果回调函数返回的不是promise,return 的promise 就会成功,value 就是返回的值
                        resolves(result)
                    }
                } catch (error) {
                    rejects(error)
                    // 传入错误
                }
            }
            // 返回一个新的promise 对象
            if (this.status == PENDING) {
                // 假设当前pending时候将回调存起来
                this.callbacks.push({
                    resolve() {
                        handle(resolve)
                    },
                    reject() {
                        handle(reject)
                    }
                })
            } else if (this.status == onRESOLVE) { // 若果当前是onRESOLVE状态 , 异步执行onRESOLVE  并改变return 的promise 状态
                setTimeout(() => {
                    handle(resolve)
                })
            } else { // onReject
                setTimeout(() => { // 若果当前是onRESOLVE状态 异步执行onRESOLVE,并改变return 的promise 状态
                    handle(reject)
                })
            }
        })
    }

    Promise.prototype.catch = function (reject) {
        return this.then(undefined, reject)
    }
    Promise.reject = function (reason) {
        return new Promise((resolve, reject) => {
            reject(reason)
        })

    }
    Promise.resolve = function (value) {
        return new Promise((resolve, reject) => {
            if (value instanceof Promise) {
                value.then(resolve, reject)
            } else {
                resolve(value)
            }
        })
    }
    Promise.all = function (promise) {}
    Promise.race = function (promise) {}

    window.Promise = Promise // 让全局的Promise = Promise 这里很重要
})(window)

 测试代码

​
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>封装promise 测试用的</title>
</head>

<body>

</body>
<script src="../promise/promise.js"></script>
<script>

    // const p = new Promise((resolve, reject) => {
    //     setTimeout(() => {
    //         // resolve(1)
    //         reject(2)
    //     });
    // }).then(
    //     value => {
    //         console.log(value);
    //     },
    //     reason => {
    //         console.log(reason)
    //         // return new Promise((resolve, reject) => {
    //         //     reject(55)
    //         // })
    //         throw 55
    //     }
    // ).then(
    //     value => {
    //         console.log(value);
    //     },
    //     reason => {
    //         console.log(reason);
    //         throw 5
    //     }
    // ).catch((reason) => {
    //     console.log(reason);
    //     // return new Promise(() => { }) // 组知下面代码执行链式调用 终止promise链
    // }).then(
    //     value => {
    //         console.log(value);
    //     },
    //     reason => {
    //         console.log(reason);
    //     }
    // )

    // let p = Promise.reject(1)
    let p = Promise.reject(1)

    p.then(
        value => {
            console.log(value);
        }, reason => {
            console.log(reason);
        }
    )
</script>

</html>

​

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有两把刷子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值