• 手撸promise【二、Promise源码】【代码详细注释/测试案例完整】


    手撸Promise即完成promise的主要功能

    • 声明构造函数
      • resolve与reject
      • throw抛出异常改变状态
      • Promise的对象状态只能修改一次
    • then方法执行回调
      • 同步任务回调的执行
      • 异步任务回调的执行
      • 指定多个回调的实现
      • 同步修改状态then方法结果返回
      • 异步修改状态then方法结果返回
    • Promise的API
      • 构造函数: then,catch
      • 函数对象: resolve,reject,all,race方法

    一、 index.html

    测试手撸的promise.js

    <!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>
        <script src="./promise.js"></script>
    </head>
    
    <body>
        <script>
            let p = new Promise((resolve, reject) => {
                resolve('OK');
                // reject("error");
                // throw "err";
    
                setTimeout(() => {
                    // resolve('OK');
                    // reject('err');
                    // ............................抛出错误该咋办。。。。。。。。。。。。。。
                    // throw "err";
                }, 1000);
            });
            console.log(p);
            // p.then(value => {
            //     console.log(value);
    
            // }, reason => {
            //     console.warn(reason);
            // })
    
    
            const res = p.then(value => {
                // alert(value);
                return 'hello';
                // return new Promise((resolve, reject) => {
                //     resolve("success");
                //     // reject("error");
                // })
                // throw "fail";
            }, reason => {
                alert(reason);
            })
    
            console.log(res);
    
            let res2 = p.catch(reason => {
                console.warn(reason);
            })
            console.log(res2);
    
            // 异常穿透,值传递
            p.then(value => {
                // console.log(111);
                // throw '失败了'
            }).then(value => {
                console.log(222);
            }).then(value => {
                console.log(333);
            }).catch(reason => {
                console.warn(reason);
            })
    
    
            // resolve方法测试用例
            const p1 = Promise.resolve('OK');
            const p2 = Promise.resolve(new Promise((resolve, reject) => {
                reject("errpr");
            }));
            const p3 = Promise.resolve(Promise.resolve('Oh Yeah!'));
    
            console.log(p1);
    
            // reject测试用例
            const r1 = Promise.reject('Error');
            const r2 = Promise.reject(new Promise((resolve, reject) => {
                resolve('ok')
            }))
            console.log(r1);
            console.log(r2);
    
            // 调用all方法
            let a1 = new Promise((resolve, reject) => {
                resolve('OK');
            })
            let a2 = Promise.resolve('Success');
            let a3 = Promise.resolve('Oh Yeah');
            let result3 = Promise.all([a1, a2, a3]);
            console.log(result3);
    
            // 调用race方法
            let ra1 = new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve('OK');
                })
            })
            let ra2 = Promise.reject('Successs');
            let ra3 = Promise.resolve('Oh Yeah!')
            let result4 = Promise.race([ra1, ra2, ra3]);
            console.log(result4);
    
            // then方法回调的异步执行
            let then1 = new Promise((resolve, reject) => {
                resolve('OK');
                console.log(111);
            })
            then1.then(value => {
                console.log(222);
            })
            console.log(333);
        </script>
    </body>
    
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116

    二、 promise.js

    function Promise(executor) {
        // 添加属性
        this.PromiseState = 'pending';
        this.PromiseResult = null;
        // 生命属性
        this.callbacks = [];
        const self = this;
    
        // resolve函数
        function resolve(data) {
            // Promise对象状态只能修改一次
            if (self.PromiseState !== 'pending') return;
            // 1. 修改对象的状态(promiseState)
            self.PromiseState = 'fulfilled';
            // 2. 设置对象结果值(promiseResult)
            self.PromiseResult = data;
            // 调用成功的回调函数
            // if (self.callback.onResolved) {
            //     self.callback.onResolved(data);
            // }
            setTimeout(() => {
                self.callbacks.forEach(item => {
                    item.onResolved(item);
                })
            })
        }
        // reject函数
        function reject(data) {
            if (self.PromiseState !== 'pending') return;
            self.PromiseState = 'rejected';
            self.PromiseResult = data;
            // 调用失败的回调函数
            // if (self.callback.onRejected) {
            //     self.callback.onRejected(data);
            // }
            setTimeout(() => {
                self.callbacks.forEach(item => {
                    item.onRejected(data);
                })
            })
        }
    
        try {
            // 同步调用【执行器函数】
            executor(resolve, reject);
        } catch (e) {
            // 修改Promise对象状态为失败
            reject(e);
        }
    }
    
    // 添加then方法
    Promise.prototype.then = function(onResolved, onRejected) {
        const self = this;
        // 判断回调函数参数->异常穿透
        if (typeof onRejected !== 'function') {
            onRejected = reason => {
                throw reason;
            }
        }
        if (typeof onResolved !== 'function') {
            onResolved = value => value;
            // value => { return value; }
        }
        return new Promise((resolve, reject) => {
            // 封装函数
            function callback(type) {
                try {
                    // 获取回调函数的执行结果
                    let result = type(self.PromiseResult);
                    // 判断
                    if (result instanceof Promise) {
                        // 如果是Promise类型的对象
                        result.then(v => {
                            resolve(v);
                        }, r => {
                            reject(r);
                        })
                    } else {
                        // 结果的对象状态为成功
                        resolve(result);
                    }
                } catch (e) {
                    reject(e);
                }
            }
            if (this.PromiseState === 'fulfilled') {
                setTimeout(() => {
                    callback(onResolved);
                })
            }
            if (this.PromiseState === 'rejected') {
                setTimeout(() => {
                    callback(onRejected);
                })
            }
            // 判断pending状态
            if (this.PromiseState === 'pending') {
                // 保存回调函数
                this.callbacks.push({
                    onResolved: function() {
                        callback(onResolved);
                    },
                    onRejected: function() {
                        callback(onRejected);
                    }
                })
            }
        })
    
    }
    
    // 添加 catch方法
    Promise.prototype.catch = function(onRejected) {
        return this.then(undefined, onRejected);
    }
    
    // 添加resolve方法
    Promise.resolve = function(value) {
        // 返回promise对象
        return new Promise((resolve, reject) => {
            if (value instanceof Promise) {
                value.then(v => {
                    resolve(v);
                }, r => {
                    reject(r);
                })
            } else {
                resolve(value);
            }
        })
    }
    
    // 添加reject方法
    Promise.reject = function(reason) {
        return new Promise((resolve, reject) => {
            reject(reason);
        })
    }
    
    // 添加all方法
    Promise.all = function(promises) {
        // 返回结果为promise对象
        return new Promise((resolve, reject) => {
            // 声明变量
            let count = 0;
            let arr = [];
            // 遍历
            for (let i = 0; i < promises.length; i++) {
                promises[i].then(v => {
                    count++;
                    arr[i] = v;
                    if (count === promises.length) {
                        // 修改状态
                        resolve(arr);
                    }
                }), r => {
                    reject(r);
                }
            }
        })
    }
    
    // 添加 race 方法
    Promise.race = function(promises) {
        return new Promise((resolve, reject) => {
            for (let i = 0; i < promises.length; i++) {
                promises[i].then(v => {
                    // 修改返回对象的状态为[成功]
                    resolve(v);
                }, r => {
                    reject(r);
                })
            }
        })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176

    三、 测试返回结果展示:

    在这里插入图片描述
    在这里插入图片描述

  • 相关阅读:
    JetBrains IDE中GPU进程(JCEF)重启问题(Too many restarts of GPU-process)解决方案
    【C++】面向对象编程(七)RTTI(运行时的鉴定机制):typeid、static_cast、dynamic_cast
    FFN -> GLU -> GAU
    将代码上传到npm中
    SpringBoot--手写组件动态更新@Value的值
    csdn最新最全pytest系列——pluggy插件源码解读(一)HookspecMarker类和HookimplMarker类分析
    MySQL面试题经典40问!(全)
    elementPuls_Treeg更改颜色
    C++ 语言学习 day10 复习(1)
    力扣每日一题
  • 原文地址:https://blog.csdn.net/hannah2233/article/details/125411509