promise-的实现

8次阅读

共计 1368 个字符,预计需要花费 4 分钟才能阅读完成。

来实现一下 Promise 内部源码

// 定义新的 Promise 类
class LxPromise{constructor(fn) {
                
                // 将成功的事件函数集成在 successList 数组里
                this.successList  = [];
                // 这里将所有的失败函数集成到 failList 里
                this.failList = []
                
                //pending,fullfilled,rejected
                
                this.state = "pending"

                // 传入的函数对象,(异步操作的函数内容)
                // 并且调用 resolveFn()和 rejectFn()方法
                // 将 resolveFn/rejectFn 和传入的 func 绑定
                //resolve() => resolveFn()
                //reject() => rejectFn()
                fn(this.resolveFn.bind(this),this.rejectFn.bind(this))
            }
            
            // 定义 then 方法, 把传入的 func 压入 list 数组
            then(successFn,failFn){if(typeof successFn=='function'){this.successList.push(successFn)
                }
                if(typeof failFn=='function'){this.failList.push(failFn)
                }
            }
            catch(failFn){if(typeof failFn=='function'){this.failList.push(failFn)
                }
            }

            // 声明 resolve 实现函数
            resolveFn(res){
                this.state = "fullfilled"
                this.successList.forEach(function(item,index){
                    // 将成功的事件循环调用
                    item(res)
                })
            }
            // 声明 reject 实现函数
            rejectFn(res){
                this.state = 'rejected'
                // 注册到的失败所有事件进行调用
                this.failList.forEach(function(item,index){item(res)
                })
                
                throw Error(res);
            }
            
        }
//******************LxPromise()构造结束 *****************

开始调用


// 参数
        var fn = function(resolve,reject){setTimeout(function(){if(true){
                    // 函数调用
                    resolve("老陈 promise 成功")
                }else{
                    // 函数调用
                    reject("老陈 promise 失败")
                }
            },1000)
        }
        
        // 创建实例对象
        var p1 = new LxPromise(fn);
        
        // 函数声明,和函数的具体操作
        p1.then(function(res){
            document.body.style.background = "greenyellow"
            console.log("这是成功做的事情")
            console.log(res)
        })
        
        p1.catch(function(res){
            document.body.style.background = "pink"
            console.log("这是失败做的事情")
            console.log(res)
        })
        

ok~ 实现!可能还不是很完整,不过旨在学习认清 promise 的实现和运作过程。

正文完
 0