本文是在后盾人大佬的带领下实现的Promise源码,看懂该源码需要了解在不同情况下的this指向以及在不同情况下的作用域链。 读者需要在了解this和作用域链之后才能看懂里面的优化和代码逻辑。
知识点总结:
- 命名函数表达式
- 匿名函数表达式
- this指向
- 作用域链
- setTimeout执行过程
这些前置知识全部掌握的情况下才能看懂下面每一句代码的逻辑。
class Seconp{
static PENDING = 'pending';
static FULLFILLED = 'fullfilled';
static REJECTED = 'rejected';
callbacks = [];
constructor(excutor) {
this.status = Seconp.PENDING;
this.value = null;
// 如果在new Promise()的过程中出现错误会进入catch。
try {
// 这里的this和new一个function中的this性质相同,this都会指向新new出来的那个数据结构
// 但是在类中的行为的this是不会自动绑定new出来的实例,this指向undefined
excutor(this.resolve.bind(this), this.rejected.bind(this))
} catch (error) {
this.reject(error)
}
}
resolve(value) {
// 这里的if判断是为了将防止状态在fullfilled和rejected之间转换
if(this.status === Seconp.PENDING) {
this.status = Seconp.FULLFILLED;
// 第一次运行的时候传递的是resolve显式调用传递的value
// 第二次运行的时候,通过let result = onFullfilled(this.value)传递的就是上一个Seconp中的value了。
// 第三次同第二次,等等
this.value = value
// 在new Seconp里面调用resolve会改变状态,会将任务变为异步任务
setTimeout(() => {
// 这里的this和作用域链具有记忆功能
// 遇到setTimeout函数首先会将函数置入任务队列中,同时记下setTimeout当前的作用域链和this
// 即使经历过再多的任务才运行到该任务,该任务运行的时候会立刻恢复记录的执行环境。
this.callbacks.map(callback => {
try {
callback.onFullfilled(value)
} catch (error) {
callback.onRejected(error)
}
})
});
}
}
rejected(reason) {
// 这里的if判断是为了将防止状态在fullfilled和rejected之间转换
if(this.status === Seconp.PENDING) {
this.status = Seconp.REJECTED;
this.value = reason
// 在new Seconp里面调用reject会改变状态,会将任务变为异步任务
setTimeout(() => {
this.callbacks.map(callback => {
try {
callback.onRejected(reason)
} catch (error) {
callback.onRejected(error)
}
})
});
}
}
then(onFullfilled, onRejected) {
if(typeof onFullfilled != 'function') {
// 将onFullfilled转化为函数,以供后面的调用
// 这里的this指向上一个实例,所以能访问this.value
// 所以实现了value/reason的链式传递,即可以通过resolve/reject来实现将值传递给下一个then/catch
onFullfilled = () => this.value
}
if(typeof onRejected != 'function') {
// 将onRejected转化为函数,以供后面的调用
// 这里的this指向上一个实例,所以能访问this.reason
// 所以实现了value/reason的链式传递,即可以通过resolve/reject来实现将值传递给下一个then/catch
onRejected = () => this.reason
}
// 实现then的链式操作----递归 + this
// 普通函数(这里Seconp是在then里面,不普通了)递归无论多少层,只是在不断压栈,但是作用域链还是很简单的,就三层 :当前作用域-->script-->global。
// Q:这里使用了什么模式?希望看到的读者能够解惑。
return new Seconp((resolve, reject) => {
// 这里的this不使用bind去绑定指定数据结构,因为调用方式是seconp.then()
// this默认指向obj,而obj是上一个new出来的实例。
// 所以这里的this指向上一个new出来的实例。
// 注意这里的函数参数,本身的上下文是then,而不是Seconp。
// 这样写更清晰:
// fun = (resolve, reject) => {......}
// return new Seconp(fun)
// 注意一个new Seconp().then()是无法调用resolve中的callback.onFullfilled(value)的,因为没有经历过向callbacks中压入对象的过程。
if(this.status === Seconp.FULLFILLED) {
// 实现异步执行
setTimeout(() => {
try {
let result = onFullfilled(this.value)
if (result instanceof Seconp) {
// 在resolve中通过this.value = value找到上一个作用域的value
// 即Seconp中传递的value
result.then(resolve, reject)
} else {
resolve(result)
}
} catch (error) {
reject(error)
}
});
}
if(this.status === Seconp.REJECTED) {
// 实现异步执行
setTimeout(() => {
try {
let result = onRejected(this.value)
if (result instanceof Seconp) {
result.then(resolve, reject)
} else {
resolve(result)
}
} catch (error) {
reject(error)
}
});
}
// 如果在new Seconp里面有异步执行的函数会先进入到PENDING状态
if(this.status === Seconp.PENDING) {
this.callbacks.push({
// 写为key/value的形式是为了使用value
onFullfilled: (value) => {
try {
let result = onFullfilled(value)
if (result instanceof Seconp) {
result.then(resolve, reject)
} else {
resolve(result)
}
} catch (error) {
reject(error)
}
},
onRejected: (reason) => {
try {
let result = onRejected(reason)
if (result instanceof Seconp) {
result.then(resolve, reject)
} else {
resolve(result)
}
} catch (error) {
reject(error)
}
}
})
}
})
}
}
测试代码
<!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="./index.js"></script>
</head>
<body>
</body>
<script>
let p = new Seconp((resolve, reject) => {
reject('拒绝')
resolve('接受');
}
).then(
value => {
return '爷爷的接受'
},
reason => {
return new Seconp((resolve, reject) => {
reject('爷爷的拒绝')
})
}
).then(
value => {
console.log('value:' + value)
},
reason => {
console.log('reason:' + reason)
}
)
</script>
</html>
结果: