手撕promise

promise的特点

1.创建时必须传入一个函数,否则会报错
2.会给传入的函数设置两个回调函数
3. 刚创建的promise对象状态是pending
4.状态一旦发生改变就不可再次改变
5.可以通过then来监听状态的改变
6.如果添加监听时状态已经改变,立即执行监听的回调
7.如果添加监听时状态还未改变,那么状态改变时候再执行监听回调
8.同一个promise对象可以添加多个then监听,状态改变时所有的监听按照添加顺序执行
9.then方法每次执行完毕都会返回一个新的promise对象
10.上一个promise对象的then可以给下一个promise的then传递数据
11.无论上一个是在成功的回调还是失败的回调传递的参数都会传递给下一个成功的回调
12.如果上一个传递的是promise对象,那么传给下一个的成果还是失败由传递的promise状态决定
13.后一个then可以捕捉前一个then的异常
14.catch方法就是then方法的语法糖then(undefined,function(){})

一、创建时必须传入一个函数,否则会报错

 <script>
        //自己创建的promise类
        class MyPromise {
            constructor(handle) {
                //1.判斷是否传入了一个函数,如果没有传入就抛出一个异常
                if (!this.isFunction(handle)) {
                    throw new Error('请传入一个函数')
                }

            }
            isFunction(fn) {
                return typeof fn === 'function'
            }

        }
        // let promise = new MyPromise()//错误示范,会抛出报错
        let promise = new MyPromise(function () { })
    </script>

在这里插入图片描述

二、会给传入的函数设置两个回调函数

 <script>
        class MyPromise {
            constructor(handle) {
                //1.判斷是否传入了一个函数,如果没有传入就抛出一个异常
                if (!this.isFunction(handle)) {
                    throw new Error('请传入一个函数')
                }
                //2.给传入的函数设置两个回调函数
                handle(this.resolve, this.reject)//*****新增
            }
            isFunction(fn) {
                return typeof fn === 'function'
            }
            //*****新增
            resolve() {
                console.log('resolve');
            }
            //*****新增
            reject() {
                console.log('reject');
            }

        }
        // let promise = new MyPromise()//错误示范,会抛出报错
        let promise = new MyPromise(function (resolve, reject) {
            //*****新增
            resolve()
            reject()
        })
    </script>

在这里插入图片描述

三、刚创建的promise对象状态是pending

 <script>
        // //****新增,先定义三种状态
        const PENDING = 'pending'
        const FULFILLED = 'fulfilled'
        const REJECTED = 'rejected'
        class MyPromise {
            constructor(handle) {
                //****新增
                // 0.默认状态为等待
                this.state = PENDING
                //1.判斷是否传入了一个函数,如果没有传入就抛出一个异常
                if (!this.isFunction(handle)) {
                    throw new Error('请传入一个函数')
                }
                //2.给传入的函数设置两个回调函数
                handle(this.resolve.bind(this), this.reject.bind(this))//****新增,这里是外部调用,只有window,所以需要将this传入
            }
            isFunction(fn) {
                return typeof fn === 'function'
            }
            resolve() {
                this.state = FULFILLED//****新增
            }
            reject() {
                this.state = REJECTED//****新增

            }

        }
        let promise = new MyPromise(function (resolve, reject) {
            resolve()
            // reject()
        })
        console.log(promise);//****新增
    </script>

在这里插入图片描述

四、状态一旦发生改变就不可再次改变

   <script>
        // 先定义三种状态
        const PENDING = 'pending'
        const FULFILLED = 'fulfilled'
        const REJECTED = 'rejected'
        class MyPromise {
            constructor(handle) {
                // 0.默认状态为等待
                this.state = PENDING
                //1.判斷是否传入了一个函数,如果没有传入就抛出一个异常
                if (!this.isFunction(handle)) {
                    throw new Error('请传入一个函数')
                }
                //2.给传入的函数设置两个回调函数
                handle(this.resolve.bind(this), this.reject.bind(this))
            }
            isFunction(fn) {
                return typeof fn === 'function'
            }
            resolve() {
                //***********新增
                // 4.状态一旦发生改变就不可再次改变
                if (this.state === PENDING) {
                    this.state = FULFILLED
                }
            }
            reject() {
                if (this.state === PENDING) {
                    this.state = REJECTED
                }

            }

        }
        let promise = new MyPromise(function (resolve, reject) {
            resolve()
            // reject()
        })
        console.log(promise);
    </script>

五、通过then来监听状态的改变,如果添加监听时状态已经改变,立即执行监听的回调

<!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>Document</title>
</head>

<body>
    <script>
        // 先定义三种状态
        const PENDING = 'pending'
        const FULFILLED = 'fulfilled'
        const REJECTED = 'rejected'
        class MyPromise {
            constructor(handle) {
                // 0.默认状态为等待
                this.state = PENDING
                //1.判斷是否传入了一个函数,如果没有传入就抛出一个异常
                if (!this.isFunction(handle)) {
                    throw new Error('请传入一个函数')
                }
                //2.给传入的函数设置两个回调函数
                handle(this.resolve.bind(this), this.reject.bind(this))
            }
            //******************新增
            // 5.通过then来监听状态的改变,如果添加监听时状态已经改变,立即执行监听的回调
            then(onResolve, onReject) {
                // (1)判断有无传入成功的函数
                if (this.isFunction(onResolve)) {
                    //(2)状态改变立即调用函数
                    if (this.state === FULFILLED) {
                        onResolve()
                    }
                }
                // (1)判断有无传入失败的函数
                if (this.isFunction(onReject)) {
                    //(2)状态改变立即调用函数
                    if (this.state === REJECTED) {
                        onReject()
                    }
                }


            }
            isFunction(fn) {
                return typeof fn === 'function'
            }
            resolve() {
                // 4.状态一旦发生改变就不可再次改变
                if (this.state === PENDING) {
                    this.state = FULFILLED
                }
            }
            reject() {
                if (this.state === PENDING) {
                    this.state = REJECTED
                }

            }

        }
        let promise = new MyPromise(function (resolve, reject) {
            // resolve()
            reject()
        })
        //******************新增
        promise.then(() => {
            console.log('成功');
        }, () => {
            console.log('失败');
        })
    </script>

</body>

</html>

在这里插入图片描述

参数传递

  <script>
        // 先定义三种状态
        const PENDING = 'pending'
        const FULFILLED = 'fulfilled'
        const REJECTED = 'rejected'
        class MyPromise {
            constructor(handle) {
                // 0.默认状态为等待
                this.state = PENDING
                // 定义变量保存传入的参数************新增
                this.value = undefined
                this.reason = undefined
                //1.判斷是否传入了一个函数,如果没有传入就抛出一个异常
                if (!this.isFunction(handle)) {
                    throw new Error('请传入一个函数')
                }
                //2.给传入的函数设置两个回调函数
                handle(this.resolve.bind(this), this.reject.bind(this))
            }
            // 5.通过then来监听状态的改变,如果添加监听时状态已经改变,立即执行监听的回调
            then(onResolve, onReject) {
                // (1)判断有无传入成功的函数
                if (this.isFunction(onResolve)) {
                    //(2)状态改变立即调用函数
                    if (this.state === FULFILLED) {
                        onResolve(this.value)//********新增变动
                    }
                }
                // (1)判断有无传入失败的函数
                if (this.isFunction(onReject)) {
                    //(2)状态改变立即调用函数
                    if (this.state === REJECTED) {
                        onReject(this.reason)//********新增变动
                    }
                }


            }
            isFunction(fn) {
                return typeof fn === 'function'
            }
            //*****新增变动
            resolve(value) {
                // 4.状态一旦发生改变就不可再次改变
                if (this.state === PENDING) {
                    this.state = FULFILLED
                    this.value = value
                }
            }
            //*****新增变动
            reject(reason) {
                if (this.state === PENDING) {
                    this.state = REJECTED
                    this.reason = reason
                }

            }

        }
        let promise = new MyPromise(function (resolve, reject) {
            resolve('111')//*****新增传参
            // reject('222')//*****新增传参
        })
        promise.then((value) => {
            console.log('成功', value);
        }, (reason) => {
            console.log('失败', reason);
        })
    </script>

在这里插入图片描述

六、如果添加监听时状态还未改变,那么状态改变时候再执行监听回调

 <script>
        // 先定义三种状态
        const PENDING = 'pending'
        const FULFILLED = 'fulfilled'
        const REJECTED = 'rejected'
        class MyPromise {
            constructor(handle) {
                // 0.默认状态为等待
                this.state = PENDING
                // 定义变量保存传入的参数
                this.value = undefined
                this.reason = undefined

                // 定义变量保存监听的函数//***新增
                this.onResolveCallback = null
                this.onRejectCallback = null
                //1.判斷是否传入了一个函数,如果没有传入就抛出一个异常
                if (!this.isFunction(handle)) {
                    throw new Error('请传入一个函数')
                }
                //2.给传入的函数设置两个回调函数
                handle(this.resolve.bind(this), this.reject.bind(this))
            }
            // 5.通过then来监听状态的改变,如果添加监听时状态已经改变,立即执行监听的回调
            then(onResolve, onReject) {
                // (1)判断有无传入成功的函数
                if (this.isFunction(onResolve)) {
                    //(2)状态改变立即调用函数
                    if (this.state === FULFILLED) {
                        onResolve(this.value)
                    }
                }
                // (1)判断有无传入失败的函数
                if (this.isFunction(onReject)) {
                    //(2)状态改变立即调用函数
                    if (this.state === REJECTED) {
                        onReject(this.reason)
                    }
                }


                // 判断状态未改变先储存//***新增
                if (this.state === PENDING) {
                    if (this.isFunction(onResolve)) {
                        this.onResolveCallback = onResolve
                    }
                    if (this.isFunction(onReject)) {
                        this.onRejectCallback = onReject
                    }
                }


            }
            isFunction(fn) {
                return typeof fn === 'function'
            }
            resolve(value) {
                // 4.状态一旦发生改变就不可再次改变
                if (this.state === PENDING) {
                    this.state = FULFILLED
                    this.value = value
                    this.onResolveCallback(this.value)//***新增
                }
            }
            reject(reason) {
                if (this.state === PENDING) {
                    this.state = REJECTED
                    this.reason = reason
                    this.onRejectCallback(this.reason)
                }

            }

        }
        let promise = new MyPromise(function (resolve, reject) {
            //***新增
            setTimeout(() => {
                resolve('111')
            }, 2000)
            // reject('222')
        })
        promise.then((value) => {
            console.log('成功', value);
        }, (reason) => {
            console.log('失败', reason);
        })
    </script>

在这里插入图片描述

七、同一个promise对象可以添加多个then监听,状态改变时所有的监听按照添加顺序执行

 <script>
        // 先定义三种状态
        const PENDING = 'pending'
        const FULFILLED = 'fulfilled'
        const REJECTED = 'rejected'
        class MyPromise {
            constructor(handle) {
                // 0.默认状态为等待
                this.state = PENDING
                // 定义变量保存传入的参数
                this.value = undefined
                this.reason = undefined

                // 定义变量保存监听的函数
                // this.onResolveCallback = null
                // this.onRejectCallback = null
                this.onResolveCallbacks = []//新增
                this.onRejectCallbacks = []//新增
                //1.判斷是否传入了一个函数,如果没有传入就抛出一个异常
                if (!this.isFunction(handle)) {
                    throw new Error('请传入一个函数')
                }
                //2.给传入的函数设置两个回调函数
                handle(this.resolve.bind(this), this.reject.bind(this))
            }
            // 5.通过then来监听状态的改变,如果添加监听时状态已经改变,立即执行监听的回调
            then(onResolve, onReject) {
                // (1)判断有无传入成功的函数
                if (this.isFunction(onResolve)) {
                    //(2)状态改变立即调用函数
                    if (this.state === FULFILLED) {
                        onResolve(this.value)
                    }
                }
                // (1)判断有无传入失败的函数
                if (this.isFunction(onReject)) {
                    //(2)状态改变立即调用函数
                    if (this.state === REJECTED) {
                        onReject(this.reason)
                    }
                }


                // 判断状态未改变先储存
                //*********新增变动
                if (this.state === PENDING) {
                    if (this.isFunction(onResolve)) {
                        // this.onResolveCallback = onResolve
                        this.onResolveCallbacks.push(onResolve)
                    }
                    if (this.isFunction(onReject)) {
                        // this.onRejectCallback = onReject
                        this.onRejectCallbacks(onReject)
                    }
                }


            }
            isFunction(fn) {
                return typeof fn === 'function'
            }
            resolve(value) {
                // 4.状态一旦发生改变就不可再次改变
                if (this.state === PENDING) {
                    this.state = FULFILLED
                    this.value = value
                    // this.onResolveCallback(this.value)
                    this.onResolveCallbacks.forEach(fn => fn(value))
                }
            }
            reject(reason) {
                if (this.state === PENDING) {
                    this.state = REJECTED
                    this.reason = reason
                    // this.onRejectCallback(this.reason)
                    this.onRejectCallback.forEach(fn => fn(value))

                }

            }

        }
        let promise = new MyPromise(function (resolve, reject) {
            resolve('111')

            // reject('222')
        })
        promise.then((value) => {
            console.log('成功', value);
        }, (reason) => {
            console.log('失败', reason);
        }); promise.then((value) => {
            console.log('成功2', value);
        }, (reason) => {
            console.log('失败2', reason);
        }); promise.then((value) => {
            console.log('成功3', value);
        }, (reason) => {
            console.log('失败3', reason);
        });
    </script>

在这里插入图片描述

八、then方法每次执行完毕都会返回一个新的promise对象

   <script>
        // 先定义三种状态
        const PENDING = 'pending'
        const FULFILLED = 'fulfilled'
        const REJECTED = 'rejected'
        class MyPromise {
            constructor(handle) {
                // 0.默认状态为等待
                this.state = PENDING
                // 定义变量保存传入的参数
                this.value = undefined
                this.reason = undefined

                // 定义变量保存监听的函数
                // this.onResolveCallback = null
                // this.onRejectCallback = null
                this.onResolveCallbacks = []
                this.onRejectCallbacks = []
                //1.判斷是否传入了一个函数,如果没有传入就抛出一个异常
                if (!this.isFunction(handle)) {
                    throw new Error('请传入一个函数')
                }
                //2.给传入的函数设置两个回调函数
                handle(this.resolve.bind(this), this.reject.bind(this))
            }
            // 5.通过then来监听状态的改变,如果添加监听时状态已经改变,立即执行监听的回调
            then(onResolve, onReject) {
                // 7.返回新promise**************新增
                return new MyPromise((nextResolve, nextReject) => {
                    // (1)判断有无传入成功的函数
                    if (this.isFunction(onResolve)) {
                        //(2)状态改变立即调用函数
                        if (this.state === FULFILLED) {
                            onResolve(this.value)
                        }
                    }
                    // (1)判断有无传入失败的函数
                    if (this.isFunction(onReject)) {
                        //(2)状态改变立即调用函数
                        if (this.state === REJECTED) {
                            onReject(this.reason)
                            console.log(22222222);
                        }
                    }


                    // 6.判断状态未改变先储存
                    if (this.state === PENDING) {
                        if (this.isFunction(onResolve)) {
                            // this.onResolveCallback = onResolve
                            this.onResolveCallbacks.push(onResolve)
                        }
                        if (this.isFunction(onReject)) {
                            // this.onRejectCallback = onReject
                            this.onRejectCallbacks.push(onReject)
                        }
                    }
                })




            }
            isFunction(fn) {
                return typeof fn === 'function'
            }
            resolve(value) {
                // 4.状态一旦发生改变就不可再次改变
                if (this.state === PENDING) {
                    this.state = FULFILLED
                    this.value = value
                    // this.onResolveCallback(this.value)
                    this.onResolveCallbacks.forEach(fn => fn(value))
                }
            }
            reject(reason) {
                if (this.state === PENDING) {
                    this.state = REJECTED
                    this.reason = reason
                    // this.onRejectCallback(this.reason)
                    this.onRejectCallbacks.forEach(fn => fn(reason))

                }

            }

        }
        let promise = new MyPromise(function (resolve, reject) {
            // resolve('111')
            reject('222')

        })
        // ****************新增
        let p2 = promise.then((value) => {
            console.log('成功', value);
        }, (reason) => {
            console.log('失败', reason);
        });
        console.log(p2, p2 === promise);
    </script>

在这里插入图片描述

九、上一个promise对象的then可以给下一个promise的then传递数据

   <script>
        // 先定义三种状态
        const PENDING = 'pending'
        const FULFILLED = 'fulfilled'
        const REJECTED = 'rejected'
        class MyPromise {
            constructor(handle) {
                // 0.默认状态为等待
                this.state = PENDING
                // 定义变量保存传入的参数
                this.value = undefined
                this.reason = undefined

                // 定义变量保存监听的函数
                // this.onResolveCallback = null
                // this.onRejectCallback = null
                this.onResolveCallbacks = []
                this.onRejectCallbacks = []
                //1.判斷是否传入了一个函数,如果没有传入就抛出一个异常
                if (!this.isFunction(handle)) {
                    throw new Error('请传入一个函数')
                }
                //2.给传入的函数设置两个回调函数
                handle(this.resolve.bind(this), this.reject.bind(this))
            }
            // 5.通过then来监听状态的改变,如果添加监听时状态已经改变,立即执行监听的回调
            then(onResolve, onReject) {
                // 7.返回新promise
                return new MyPromise((nextResolve, nextReject) => {
                    // (1)判断有无传入成功的函数
                    if (this.isFunction(onResolve)) {
                        //(2)状态改变立即调用函数
                        if (this.state === FULFILLED) {
                            //*******新增
                            // 接收返回并传递给下一个promise
                            let result = onResolve(this.value)
                            nextResolve(result)
                        }
                    }
                    // (1)判断有无传入失败的函数
                    if (this.isFunction(onReject)) {
                        //(2)状态改变立即调用函数
                        if (this.state === REJECTED) {
                            let result = onReject(this.reason)
                            nextReject(result)
                        }
                    }


                    // 6.判断状态未改变先储存
                    if (this.state === PENDING) {
                        if (this.isFunction(onResolve)) {
                            // this.onResolveCallback = onResolve
                            //**********新增变动
                            this.onResolveCallbacks.push(() => {
                                let result = onResolve(this.value)
                                nextResolve(result)
                            })
                        }
                        if (this.isFunction(onReject)) {
                            // this.onRejectCallback = onReject
                            this.onRejectCallbacks.push(() => {
                                let result = onReject(this.reason)
                                nextReject(result)
                            })
                        }
                    }
                })




            }
            isFunction(fn) {
                return typeof fn === 'function'
            }
            resolve(value) {
                // 4.状态一旦发生改变就不可再次改变
                if (this.state === PENDING) {
                    this.state = FULFILLED
                    this.value = value
                    // this.onResolveCallback(this.value)
                    this.onResolveCallbacks.forEach(fn => fn(value))
                }
            }
            reject(reason) {
                if (this.state === PENDING) {
                    this.state = REJECTED
                    this.reason = reason
                    // this.onRejectCallback(this.reason)
                    this.onRejectCallbacks.forEach(fn => fn(reason))

                }

            }

        }
        let promise = new MyPromise(function (resolve, reject) {
            // resolve('111')
            // reject('222')
            setTimeout(() => {
                resolve('111')
            }, 2000)

        })
        let p2 = promise.then((value) => {
            console.log('成功', value);
            return '我是p2成功返回'
        }, (reason) => {
            console.log('失败', reason);
            return '我是p2失败返回'
        });

        p2.then((value) => {
            console.log('成功2', value);
        }, (reason) => {
            console.log('失败2', reason);
        });

    </script>

在这里插入图片描述

十、如果上一个传递的是promise对象,那么传给下一个的成果还是失败由传递的promise状态决定

 <script>
        // 先定义三种状态
        const PENDING = 'pending'
        const FULFILLED = 'fulfilled'
        const REJECTED = 'rejected'
        class MyPromise {
            constructor(handle) {
                // 0.默认状态为等待
                this.state = PENDING
                // 定义变量保存传入的参数
                this.value = undefined
                this.reason = undefined

                // 定义变量保存监听的函数
                // this.onResolveCallback = null
                // this.onRejectCallback = null
                this.onResolveCallbacks = []
                this.onRejectCallbacks = []
                //1.判斷是否传入了一个函数,如果没有传入就抛出一个异常
                if (!this.isFunction(handle)) {
                    throw new Error('请传入一个函数')
                }
                //2.给传入的函数设置两个回调函数
                handle(this.resolve.bind(this), this.reject.bind(this))
            }
            // 5.通过then来监听状态的改变,如果添加监听时状态已经改变,立即执行监听的回调
            then(onResolve, onReject) {
                // 7.返回新promise
                return new MyPromise((nextResolve, nextReject) => {
                    // (1)判断有无传入成功的函数
                    if (this.isFunction(onResolve)) {
                        //(2)状态改变立即调用函数
                        if (this.state === FULFILLED) {
                            // 接收返回并传递给下一个promise
                            let result = onResolve(this.value)
                            // 8.判断如果是返回的promise,则等待执行
                            //************新增
                            if (result instanceof MyPromise) {
                                result.then(nextResolve, nextReject)
                            } else {
                                nextResolve(result)
                            }

                        }
                    }
                    // (1)判断有无传入失败的函数
                    if (this.isFunction(onReject)) {
                        //(2)状态改变立即调用函数
                        if (this.state === REJECTED) {
                            let result = onReject(this.reason)
                            //************新增
                            if (result instanceof MyPromise) {
                                result.then(nextResolve, nextReject)
                            } else {
                                nextReject(result)
                            }
                        }
                    }


                    // 6.判断状态未改变先储存
                    if (this.state === PENDING) {
                        if (this.isFunction(onResolve)) {
                            // this.onResolveCallback = onResolve
                            this.onResolveCallbacks.push(() => {
                                let result = onResolve(this.value)
                                //************新增
                                if (result instanceof MyPromise) {
                                    result.then(nextResolve, nextReject)
                                } else {
                                    nextResolve(result)
                                }
                            })
                        }
                        if (this.isFunction(onReject)) {
                            // this.onRejectCallback = onReject
                            this.onRejectCallbacks.push(() => {
                                let result = onReject(this.reason)
                                //*******8新增
                                if (result instanceof MyPromise) {
                                    result.then(nextResolve, nextReject)
                                } else {
                                    nextReject(result)
                                }
                            })
                        }
                    }
                })




            }
            isFunction(fn) {
                return typeof fn === 'function'
            }
            resolve(value) {
                // 4.状态一旦发生改变就不可再次改变
                if (this.state === PENDING) {
                    this.state = FULFILLED
                    this.value = value
                    // this.onResolveCallback(this.value)
                    this.onResolveCallbacks.forEach(fn => fn(value))
                }
            }
            reject(reason) {
                if (this.state === PENDING) {
                    this.state = REJECTED
                    this.reason = reason
                    // this.onRejectCallback(this.reason)
                    this.onRejectCallbacks.forEach(fn => fn(reason))

                }

            }

        }
        let promise = new MyPromise(function (resolve, reject) {
            // resolve('111')
            reject('222')
            // setTimeout(() => {
            //     resolve('111')
            // }, 2000)

        })

        //********新增
        let ppp = new MyPromise((resolve, reject) => {
            // resolve('我是被传递的promise成功')
            reject('我是被传递的promise失败')
            // setTimeout(() => {
            //     resolve('我是被传递的promise成功延时')
            // }, 2000)

        })
        let p2 = promise.then((value) => {
            console.log('成功', value);
            return ppp//*********新增
        }, (reason) => {
            console.log('失败', reason);
            return ppp
        });

        p2.then((value) => {
            console.log('成功2', value);
        }, (reason) => {
            console.log('失败2', reason);
        });

    </script>

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值