promise的自定义封装

Promise 自定义封装

1. 初始结构搭建

<script>
        // 实例化对象
        let p = new Promise((resolve, reject) => {
            resolve('OK')
        })

        p.then(value => {
            console.log(value);
        }, reason => {
            console.warn(reason);
        })
script>
function Promise(executor) {

}

// 添加 then 方法
Promise.prototype.then = function (onResolved, onRejected) {

}

2. resolve 与 reject 结构搭建

function Promise(executor) {
    // resolve 函数
    function resolve(data) {

    }
    // reject 函数
    function reject(data) {

    }
    // 同步调用 【执行器函数】
    executor(resolve, reject)
}

// // 添加 then 方法
Promise.prototype.then = function (onResolved, onRejected) {

}

3. resolve 与 reject 代码实现

<script>
        // 实例化对象
        let p = new Promise((resolve, reject) => {
            resolve('OK')
        })
        
        console.log(p);

        p.then(value => {
            console.log(value);
        }, reason => {
            console.warn(reason);
        })
script>
function Promise(executor) {
    // 添加属性
    this.PromiseState = 'pending'
    this.PromiseResult = null
    // 保存实例对象的 this 的值
    const self = this
    // resolve 函数
    function resolve(data) {
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'fulfilled'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
    }
    // reject 函数
    function reject(data) {
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'rejected'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
    }
    // 同步调用 【执行器函数】
    executor(resolve, reject)
}

// // 添加 then 方法
Promise.prototype.then = function (onResolved, onRejected) {

}

4. throw 抛出异常改变状态

<script>
        // 实例化对象
        let p = new Promise((resolve, reject) => {
            // resolve('OK')
            throw new Error('error')
        })

        console.log(p);

        p.then(value => {
            console.log(value);
        }, reason => {
            console.warn(reason);
        })
script>
function Promise(executor) {
    // 添加属性
    this.PromiseState = 'pending'
    this.PromiseResult = null
    // 保存实例对象的 this 的值
    const self = this
    // resolve 函数
    function resolve(data) {
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'fulfilled'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
    }
    // reject 函数
    function reject(data) {
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'rejected'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
    }
    try {
        // 同步调用 【执行器函数】
        executor(resolve, reject)
    } catch (error) {
        // 修改 Promise 对象的状态为失败
        reject(error)
    }
}

// // 添加 then 方法
Promise.prototype.then = function (onResolved, onRejected) {

}

5. Promise 对象只能修改一次

<script>
        // 实例化对象
        let p = new Promise((resolve, reject) => {
            resolve('OK')
            reject('error')
            // throw new Error('error')
        })

        console.log(p);

        p.then(value => {
            console.log(value);
        }, reason => {
            console.warn(reason);
        })
script>
function Promise(executor) {
    // 添加属性
    this.PromiseState = 'pending'
    this.PromiseResult = null
    // 保存实例对象的 this 的值
    const self = this
    // resolve 函数
    function resolve(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'fulfilled'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
    }
    // reject 函数
    function reject(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'rejected'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
    }
    try {
        // 同步调用 【执行器函数】
        executor(resolve, reject)
    } catch (error) {
        // 修改 Promise 对象的状态为失败
        reject(error)
    }
}

// // 添加 then 方法
Promise.prototype.then = function (onResolved, onRejected) {

}

6. then 方法执行回调

<script>
        // 实例化对象
        let p = new Promise((resolve, reject) => {
            // resolve('OK')
            reject('error')
            // throw new Error('error')
        })

        console.log(p);

        p.then(value => {
            console.log(value);
        }, reason => {
            console.warn(reason);
        })
    script>
function Promise(executor) {
    // 添加属性
    this.PromiseState = 'pending'
    this.PromiseResult = null
    // 保存实例对象的 this 的值
    const self = this
    // resolve 函数
    function resolve(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'fulfilled'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
    }
    // reject 函数
    function reject(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'rejected'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
    }
    try {
        // 同步调用 【执行器函数】
        executor(resolve, reject)
    } catch (error) {
        // 修改 Promise 对象的状态为失败
        reject(error)
    }
}

// // 添加 then 方法
Promise.prototype.then = function (onResolved, onRejected) {
    // 当对象的 PromiseState 属性为 fulfilled,执行 onResolved
    if (this.PromiseState === 'fulfilled') {
        onResolved(this.PromiseResult)
    }
    // 当对象的 PromiseState 属性为 rejected,执行 onRejected
    if (this.PromiseState === 'rejected') {
        onRejected(this.PromiseResult)
    }
}

7. 异步任务回调的执行

<script>
        // 实例化对象
        let p = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('OK')
            }, 1000);
        })

        p.then(value => {
            console.log(value);
        }, reason => {
            console.warn(reason);
        })
    
    	console.log(p);
script>
function Promise(executor) {
    // 添加属性
    this.PromiseState = 'pending'
    this.PromiseResult = null
    this.callbacks = {}
    // 保存实例对象的 this 的值
    const self = this
    // resolve 函数
    function resolve(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'fulfilled'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
        // 执行成功的回调函数
        if (self.callbacks.onResolved) {
            self.callbacks.onResolved(data)
        }
    }
    // reject 函数
    function reject(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'rejected'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
        // 执行失败的回调函数
        if (self.callbacks.onRejected) {
            self.callbacks.onRejected(data)
        }
    }
    try {
        // 同步调用 【执行器函数】
        executor(resolve, reject)
    } catch (error) {
        // 修改 Promise 对象的状态为失败
        reject(error)
    }
}

// // 添加 then 方法
Promise.prototype.then = function (onResolved, onRejected) {
    // 当对象的 PromiseState 属性为 fulfilled,执行 onResolved
    if (this.PromiseState === 'fulfilled') {
        onResolved(this.PromiseResult)
    }
    // 当对象的 PromiseState 属性为 rejected,执行 onRejected
    if (this.PromiseState === 'rejected') {
        onRejected(this.PromiseResult)
    }
    // 当对象的 PromiseState 属性为 pending,则说明执行了一个异步操作
    if (this.PromiseState === 'pending') {
        // 保存回调函数
        this.callbacks = {
            onResolved: onResolved,
            onRejected: onRejected
        }
    }
}

8. 指定多个回调的实现

<script>
        // 实例化对象
        let p = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('OK')
            }, 1000);
        })

        p.then(value => {
            console.log(value);
        }, reason => {
            console.warn(reason);
        })
    
        p.then(value => {
            alert(value);
        }, reason => {
            console.warn(reason);
        })
    
   	 	console.log(p);
script>
function Promise(executor) {
    // 添加属性
    this.PromiseState = 'pending'
    this.PromiseResult = null
    this.callbacks = []
    // 保存实例对象的 this 的值
    const self = this
    // resolve 函数
    function resolve(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'fulfilled'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
        // 执行成功的回调函数
        self.callbacks.forEach(item => {
            item.onResolved(data)
        })
    }
    // reject 函数
    function reject(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'rejected'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
        // 执行失败的回调函数
        self.callbacks.forEach(item => {
            item.onRejected(data)
        })
    }
    try {
        // 同步调用 【执行器函数】
        executor(resolve, reject)
    } catch (error) {
        // 修改 Promise 对象的状态为失败
        reject(error)
    }
}

// // 添加 then 方法
Promise.prototype.then = function (onResolved, onRejected) {
    // 当对象的 PromiseState 属性为 fulfilled,执行 onResolved
    if (this.PromiseState === 'fulfilled') {
        onResolved(this.PromiseResult)
    }
    // 当对象的 PromiseState 属性为 rejected,执行 onRejected
    if (this.PromiseState === 'rejected') {
        onRejected(this.PromiseResult)
    }
    // 当对象的 PromiseState 属性为 pending,则说明执行了一个异步操作
    if (this.PromiseState === 'pending') {
        // 保存回调函数
        this.callbacks.push({
            onResolved: onResolved,
            onRejected: onRejected
        })
    }
}

9. 同步修改状态 then 方法结果返回

<script>
        // 实例化对象
        let p = new Promise((resolve, reject) => {
            resolve('OK')
        })

        let res = p.then(value => {
            console.log(value);
            // return value
            // throw new Error('error')
            return new Promise((resolve, reject) => {
                reject('error')
            })
        }, reason => {
            console.warn(reason);
        })

        console.log(res);

script>
function Promise(executor) {
    // 添加属性
    this.PromiseState = 'pending'
    this.PromiseResult = null
    this.callbacks = []
    // 保存实例对象的 this 的值
    const self = this
    // resolve 函数
    function resolve(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'fulfilled'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
        // 执行成功的回调函数
        self.callbacks.forEach(item => {
            item.onResolved(data)
        })
    }
    // reject 函数
    function reject(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'rejected'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
        // 执行失败的回调函数
        self.callbacks.forEach(item => {
            item.onRejected(data)
        })
    }
    try {
        // 同步调用 【执行器函数】
        executor(resolve, reject)
    } catch (error) {
        // 修改 Promise 对象的状态为失败
        reject(error)
    }
}

// // 添加 then 方法
Promise.prototype.then = function (onResolved, onRejected) {
    return new Promise((resolve, reject) => {
        // 当对象的 PromiseState 属性为 fulfilled,执行 onResolved
        if (this.PromiseState === 'fulfilled') {
            try {
                let result = onResolved(this.PromiseResult)
                if (result instanceof Promise) {
                    result.then(v => {
                        resolve(v)
                    }, r => {
                        reject(r)
                    })
                } else {
                    resolve(result)
                }
            } catch (error) {
                reject(error)
            }
        }

        // 当对象的 PromiseState 属性为 rejected,执行 onRejected
        if (this.PromiseState === 'rejected') {
            onRejected(this.PromiseResult)
        }
        // 当对象的 PromiseState 属性为 pending,则说明执行了一个异步操作
        if (this.PromiseState === 'pending') {
            // 保存回调函数
            this.callbacks.push({
                onResolved: onResolved,
                onRejected: onRejected
            })
        }
    })

}

10. 异步修改状态 then 方法结果返回

<script>
        // 实例化对象
        let p = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('OK')
            }, 1000);
        })

        let res = p.then(value => {
            console.log(value);
            return value
            // throw new Error('error')
        }, reason => {
            console.warn(reason);
        })

        console.log(res);

script>
function Promise(executor) {
    // 添加属性
    this.PromiseState = 'pending'
    this.PromiseResult = null
    this.callbacks = []
    // 保存实例对象的 this 的值
    const self = this
    // resolve 函数
    function resolve(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'fulfilled'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
        // 执行成功的回调函数
        self.callbacks.forEach(item => {
            item.onResolved(data)
        })
    }
    // reject 函数
    function reject(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'rejected'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
        // 执行失败的回调函数
        self.callbacks.forEach(item => {
            item.onRejected(data)
        })
    }
    try {
        // 同步调用 【执行器函数】
        executor(resolve, reject)
    } catch (error) {
        // 修改 Promise 对象的状态为失败
        reject(error)
    }
}

// // 添加 then 方法
Promise.prototype.then = function (onResolved, onRejected) {
    const self = this
    return new Promise((resolve, reject) => {
        // 当对象的 PromiseState 属性为 fulfilled,执行 onResolved
        if (this.PromiseState === 'fulfilled') {
            try {
                let result = onResolved(this.PromiseResult)
                if (result instanceof Promise) {
                    result.then(v => {
                        resolve(v)
                    }, r => {
                        reject(r)
                    })
                } else {
                    resolve(result)
                }
            } catch (error) {
                reject(error)
            }
        }

        // 当对象的 PromiseState 属性为 rejected,执行 onRejected
        if (this.PromiseState === 'rejected') {
            onRejected(this.PromiseResult)
        }
        // 当对象的 PromiseState 属性为 pending,则说明执行了一个异步操作
        if (this.PromiseState === 'pending') {
            // 保存回调函数
            this.callbacks.push({
                onResolved: function () {
                    try {
                        let result = onResolved(self.PromiseResult)
                        if (result instanceof Promise) {
                            result.then(v => {
                                resolve(v)
                            }, r => {
                                reject(r)
                            })
                        } else {
                            reject(result)
                        }
                    } catch (error) {
                        reject(error)
                    }
                },
                onRejected: function () {
                    try {
                        let result = onRejected(self.PromiseResult)
                        if (result instanceof Promise) {
                            result.then(v => {
                                resolve(v)
                            }, r => {
                                reject(r)
                            })
                        } else {
                            reject(result)
                        }
                    } catch (error) {
                        reject(error)
                    }
                }
            })
        }
    })
}

11. then 方法完善与优化

function Promise(executor) {
    // 添加属性
    this.PromiseState = 'pending'
    this.PromiseResult = null
    this.callbacks = []
    // 保存实例对象的 this 的值
    const self = this
    // resolve 函数
    function resolve(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'fulfilled'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
        // 执行成功的回调函数
        self.callbacks.forEach(item => {
            item.onResolved(data)
        })
    }
    // reject 函数
    function reject(data) {
        // 判断状态
        if (self.PromiseState !== 'pending') return
        // 1. 修改对象的属性 (PromiseState)
        self.PromiseState = 'rejected'
        // 2. 修改对象的结果值 (PromiseResult)
        self.PromiseResult = data
        // 执行失败的回调函数
        self.callbacks.forEach(item => {
            item.onRejected(data)
        })
    }
    try {
        // 同步调用 【执行器函数】
        executor(resolve, reject)
    } catch (error) {
        // 修改 Promise 对象的状态为失败
        reject(error)
    }
}

// // 添加 then 方法
Promise.prototype.then = function (onResolved, onRejected) {
    const self = this
    return new Promise((resolve, reject) => {
        function callback(type) {
            try {
                let result = type(self.PromiseResult)
                if (result instanceof Promise) {
                    result.then(v => {
                        resolve(v)
                    }, r => {
                        reject(r)
                    })
                } else {
                    resolve(result)
                }
            } catch (error) {
                reject(error)
            }
        }

        // 当对象的 PromiseState 属性为 fulfilled,执行 onResolved
        if (this.PromiseState === 'fulfilled') {
            callback(onResolved)
        }

        // 当对象的 PromiseState 属性为 rejected,执行 onRejected
        if (this.PromiseState === 'rejected') {
            callback(onRejected)
        }
        // 当对象的 PromiseState 属性为 pending,则说明执行了一个异步操作
        if (this.PromiseState === 'pending') {
            // 保存回调函数
            this.callbacks.push({
                onResolved: function () {
                    callback(onResolved)
                },
                onRejected: function () {
                    callback(onRejected)
                }
            })
        }
    })
}

你可能感兴趣的:(javascript,es6)