前端面经 手写Promise
核心功能
仿Promise对象需要接收包含两个变量的回调函数
构造函数
<script>class myPromise {constructor(func){const resolve = (result)=>{console.log(`resolve执行了`)}const reject = (result)=>{console.log(`reject执行了`)}func(resolve,reject)}}// Promise的构造函数传入一个resolve值调用构造函数外部定义好的resolve 和 reject方法const pro = new myPromise((resolve,reject)=>{console.log(`Promise内的同步部分被实现了`)resolve(`succeed`)})</script>
状态及其原因
为Promise类对象添加实例状态state和原因result,并且改变状态也不可逆仅限pending状态可变
class myPromise {// 添加实例属性 statestate = pending// 添加原因属性 resultresult = undefinedconstructor(func){const resolve = (result)=>{// 改状态statethis.state = fullfilled// 原因传参 this.result =result}const reject = (result)=>{// 改状态statethis.state = reject// 原因传参 this.result =result}func(resolve,reject)}}
为Promise类添加实例属性state和result 为实现隔离状态改变
加上条件判断当state是pending时再进行改动
<script>// 状态常量 定义const pending = `pending`const fullfilled = `fullfilled`const reject = `reject`class myPromise {// 添加实例属性 statestate = pending// 添加原因属性 resultresult = undefinedconstructor(func){const resolve = (result)=>{if(this.state===pending){// 改状态statethis.state = fullfilled// 原因传参 this.result =result}}const reject = (result)=>{if(this.state===pending){// 改状态statethis.state = reject// 原因传参 this.result =result}}func(resolve,reject)}}// Promise的构造函数传入一个resolve值调用构造函数外部定义好的resolve 和 reject方法const pro = new myPromise((resolve,reject)=>{console.log(`Promise内的同步部分被实现了`)resolve(`404 没找到`)})</script>
实现步骤 :1为myPromise添加实例状态state和实例结果result 2.修改result()
then方法
设想这样的then()和catch() 方法大概要挂载在myPromise类的prototype原型对象上
参数判断 then()中传递的参数是否为两个回调函数
class myPromise {// 添加实例属性 statestate = pending// 添加原因属性 resultresult = undefinedconstructor(func){const resolve = (result)=>{if(this.state===pending){// 改状态statethis.state = fullfilled// 原因传参 this.result =resultconsole.log(`成功`)}}const reject = (result)=>{if(this.state===pending){// 改状态statethis.state = reject// 原因传参 this.result =result}}func(resolve,reject)}// 添加实例方法 then接收两个回调函数作为参数then(onFullfilled,onRejected){// 实参为空的情况onFullfilled = onFullfilled === `function`?onFullfilled:(x)=>{return x}onRejected = onRejected === `function`?onRejected:(x)=>{throw x}}}
class myPromise {// 添加实例属性 statestate = pending// 添加原因属性 resultresult = undefinedconstructor(func){const resolve = (result)=>{if(this.state===pending){// 改状态statethis.state = fullfilled// 原因传参 this.result =resultconsole.log(`状态变更为成功`)}}const reject = (result)=>{if(this.state===pending){// 改状态statethis.state = Reject// 原因传参 this.result =resultconsole.log(`状态变更为失败`)}}func(resolve,reject)}// 添加实例方法 then接收两个回调函数作为参数then(onFullfilled,onRejected){// 实参为空的情况onFullfilled = typeof onFullfilled === `function`?onFullfilled:(x)=>{return x}onRejected = typeof onRejected === `function`?onRejected:(x)=>{throw x}// 根据状态执行函数if(this.state===fullfilled){onFullfilled(this.result)}else if(this.state===Reject){onRejected(this.result)}}}