Promise自定义封装
前言
本文作为本人学习总结之用,以笔记为主,同时分享给大家.
本篇文章是B站尚硅谷最新Promise视频的部分笔记
因为个人技术有限,如果有发现错误或存在疑问之处,欢迎指出或指点!不胜感谢!
基本原理
Promise 是一个类,在执行这个类的时候会传入一个执行器,这个执行器会立即执行
Promise 会有三种状态
Pending 等待
Fulfilled 完成
Rejected 失败
状态只能由 Pending --> Fulfilled 或者 Pending --> Rejected,且一但发生改变便不可二次修改;
Promise 中使用 resolve 和 reject 两个函数来更改状态;
then 方法内部做但事情就是状态判断
如果状态是成功,调用成功回调函数
如果状态是失败,调用失败回调函数
和上篇文章"Promise关键问题"
了解以上基本原理和关键问题之后,为手写Promise准备
一、Promise 基本实现
1.初始结构搭建
首先使用函数式编写便于理解
//Promise.js //声明构造函数 function Promise(executor){ //resolve 函数 function resolve(data){} //reject 函数 function reject(data){} //同步调用『执行器函数』 executor(resolve, reject); } //添加 then 方法 Promise.prototype.then = function(onResolved, onRejected){ } 复制代码
2.resolve与reject函数实现
//Promise.js //声明构造函数 function Promise(executor){ //添加属性 this.PromiseState = 'pending'; this.PromiseResult = null; //保存实例对象的 this 的值 const self = this;// self _this that //resolve 函数 function resolve(data){ //1. 修改对象的状态 (promiseState) self.PromiseState = 'fulfilled';// resolved //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){ } 复制代码
3.状态只能修改一次
使用我们写的Promise输出状态不对,状态只能修改一次
let p = new Promise((resolve, reject) => { reject("error"); resolve('OK'); }); console.log(p); //输出的状态是 PromiseState: "fulfilled" PromiseResult: "OK" 复制代码
这时候需要将resolve和reject函数,当状态不等于pending直接return
//Promis.js //resolve 函数 function resolve(data){ //判断状态 if(self.PromiseState !== 'pending') return; //1. 修改对象的状态 (promiseState) self.PromiseState = 'fulfilled';// resolved //2. 设置对象结果值 (promiseResult) self.PromiseResult = data; } //reject 函数 function reject(data){ //判断状态 if(self.PromiseState !== 'pending') return; //1. 修改对象的状态 (promiseState) self.PromiseState = 'rejected';// //2. 设置对象结果值 (promiseResult) self.PromiseResult = data; } 复制代码
4.简单then方法执行回调
//Promis.js //添加 then 方法 Promise.prototype.then = function(onResolved, onRejected){ //调用回调函数 PromiseState if(this.PromiseState === 'fulfilled'){ onResolved(this.PromiseResult); } if(this.PromiseState === 'rejected'){ onRejected(this.PromiseResult); } } 复制代码
5.throw抛出错误改变状态
我们知道在promise中可以抛出异常,则需要在我们写的Promise中去捕获异常
let p = new Promise((resolve, reject) => { //抛出异常 throw "error"; }); console.log(p); //Promise.js try{ //同步调用『执行器函数』 executor(resolve, reject); }catch(e){ //修改 promise 对象状态为『失败』 reject(e); } 复制代码
目前完成代码为
//Promise.js //声明构造函数 function Promise(executor){ //添加属性 this.PromiseState = 'pending'; this.PromiseResult = null; //保存实例对象的 this 的值 const self = this;// self _this that //resolve 函数 function resolve(data){ //判断状态 if(self.PromiseState !== 'pending') return; //1. 修改对象的状态 (promiseState) self.PromiseState = 'fulfilled';// resolved //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(e){ //修改 promise 对象状态为『失败』 reject(e); } } //添加 then 方法 Promise.prototype.then = function(onResolved, onRejected){ //调用回调函数 PromiseState if(this.PromiseState === 'fulfilled'){ onResolved(this.PromiseResult); } if(this.PromiseState === 'rejected'){ onRejected(this.PromiseResult); } } 复制代码
使用手写代码测试一下
//实例化对象 let p = new Promise((resolve, reject) => { resolve('OK'); reject("Error"); }); p.then(value => { console.log(value); }, reason=>{ console.warn(reason); }) //执行结果:OK Error 复制代码
打印正常符合正常效果
二、Promise异步封装
1.异步任务then方法执行回调
直接运行下面代码,输出为Promise,本来then方法是需要调用的,现在没有,需要在then方法保存回调函数
//实例化对象 let p = new Promise((resolve, reject) => { setTimeout(() => { // resolve('OK'); reject("error"); }, 1000); }); p.then(value => { console.log(value); }, reason=>{ console.warn(reason); }); console.log(p); 复制代码
//Promise.js then中添加判断 Promise.prototype.then = function(onResolved, onRejected){ //调用回调函数 PromiseState if(this.PromiseState === 'fulfilled'){ onResolved(this.PromiseResult); } if(this.PromiseState === 'rejected'){ onRejected(this.PromiseResult); } //判断 pending 状态 if(this.PromiseState === 'pending'){ //保存回调函数 this.callback = { onResolved: onResolved, onRejected: onRejected } } } //在promise构造函数 reject和resolve调用成功和失败的回调 //resolve 函数 function resolve(data){ //判断状态 if(self.PromiseState !== 'pending') return; //1. 修改对象的状态 (promiseState) self.PromiseState = 'fulfilled';// resolved //2. 设置对象结果值 (promiseResult) self.PromiseResult = data; //调用成功的回调函数 if(self.callback.onResolved){ self.callback.onResolved(data); } } //reject 函数 function reject(data){ //判断状态 if(self.PromiseState !== 'pending') return; //1. 修改对象的状态 (promiseState) self.PromiseState = 'rejected';// //2. 设置对象结果值 (promiseResult) self.PromiseResult = data; //执行回调 if(self.callback.onResolved){ self.callback.onResolved(data); } } 复制代码
2.指定多个回调
当我们对于用一个Promise指定多个回调时,则只会运行最后一个then方法,需要对以上进行修改
//Promise.js //在promise构造函数 resolve和reject调用成功和失败的回调 //声明属性 this.callbacks = []; //resolve 函数 function resolve(data){ //判断状态 if(self.PromiseState !== 'pending') return; //1. 修改对象的状态 (promiseState) self.PromiseState = 'fulfilled';// resolved //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); }); } //then中添加判断 Promise.prototype.then = function(onResolved, onRejected){ //调用回调函数 PromiseState if(this.PromiseState === 'fulfilled'){ onResolved(this.PromiseResult); } if(this.PromiseState === 'rejected'){ onRejected(this.PromiseResult); } //判断 pending 状态 if(this.PromiseState === 'pending'){ //保存回调函数 this.callbacks.push({ onResolved: onResolved, onRejected: onRejected }); } } 复制代码
3.同步和异步修改状态then方法返回结果
当我们调用自己的方法时,then方法第一个回调如果抛出错误的话,应该返回一个失败的Promise
//实例化对象 let p = new Promise((resolve, reject) => { setTimeout(() => { resolve('OK'); // reject("Error"); }, 1000) }); //执行 then 方法 const res = p.then(value => { // return 'oh Yeah'; throw 'error'; }, reason=>{ // console.warn(reason); throw 'error'; }); console.log(res); 复制代码
//Promise.js //添加 then 方法 Promise.prototype.then = function(onResolved, onRejected){ const self = this; return new Promise((resolve, reject) => { //封装函数 function callback(type){ //获取回调函数的执行结果 let result = type(self.PromiseResult); //判断 if(result instanceof Promise){ //如果是 Promise 类型的对象 result.then(v => { resolve(v); }, r=>{ reject(r); }) }else{ //结果的对象状态为『成功』 resolve(result); } } //调用回调函数 PromiseState if(this.PromiseState === 'fulfilled'){ callback(onResolved); } if(this.PromiseState === 'rejected'){ callback(onRejected); } //判断 pending 状态 if(this.PromiseState === 'pending'){ //保存回调函数 this.callbacks.push({ onResolved: function(){ callback(onResolved); }, onRejected: function(){ callback(onRejected); } }); } }) } 复制代码
4.catch方法与异常穿透
//添加 catch 方法 Promise.prototype.catch = function(onRejected){ return this.then(undefined, onRejected); } 复制代码
5.then回调函数异步执行的实现
then方法完善
//Promise.js //添加 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; } return new Promise((resolve, reject) => { //封装函数 function callback(type){ //获取回调函数的执行结果 let result = type(self.PromiseResult); //判断 if(result instanceof Promise){ //如果是 Promise 类型的对象 result.then(v => { resolve(v); }, r=>{ reject(r); }) }else{ //结果的对象状态为『成功』 resolve(result); } } //调用回调函数 PromiseState 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); } }); } }) } 复制代码
目前为止手写基本完成,只有Promise方法未实现了
完整代码
//promise.js //声明构造函数 function Promise(executor){ //添加属性 this.PromiseState = 'pending'; this.PromiseResult = null; //声明属性 this.callbacks = []; //保存实例对象的 this 的值 const self = this;// self _this that //resolve 函数 function resolve(data){ //判断状态 if(self.PromiseState !== 'pending') return; //1. 修改对象的状态 (promiseState) self.PromiseState = 'fulfilled';// resolved //2. 设置对象结果值 (promiseResult) self.PromiseResult = data; //调用成功的回调函数 setTimeout(() => { 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; //执行失败的回调 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){ //获取回调函数的执行结果 let result = type(self.PromiseResult); //判断 if(result instanceof Promise){ //如果是 Promise 类型的对象 result.then(v => { resolve(v); }, r=>{ reject(r); }) }else{ //结果的对象状态为『成功』 resolve(result); } } //调用回调函数 PromiseState 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); }
作者:Moons
链接:https://juejin.cn/post/7020316864664305694