promise就是构造函数 使用是发布订阅模式 我们定义三个状态
const PENDING = "pending"
const FULFILLED = "fulfilled"
const REJECTED = "rejected"
代码里面的注释,可以看下
class Promise {
constructor(executor) {
this.status = PENDING
this.value = undefined
this.reson = undefined
this.resolveCall = []
this.rejectCall = []
let resolve = (value) => {
if (this.status === PENDING) {
this.status = FULFILLED
this.value = value
this.resolveCall.forEach((fn=> {
fn()
}))
}
}
let reject = (reson) => {
if (this.status === PENDING) {
this.status = REJECTED
this.reson = reson
this.rejectCall.forEach((fn=> {
fn()
}))
}
}
try {
executor(resolve, reject)
} catch (error) {
reject(error)
}
}
then(onResolve, onReject) {
if (this.status === FULFILLED) {
onResolve(this.value)
}
if (this.status === REJECTED) {
onReject(this.reson)
}
if(this.status === PENDING) {
this.resolveCall.push(()=> {
onResolve(this.value)
})
this.rejectCall.push(()=> {
onReject(this.reson)
})
}
}
}
module.exports = Promise
这里有一点可能会有一点难以理解 p.then调用后 this.status === PENDING 其实就是宏观任务最后执行 关于这个异步调用可能有一点难以理解的, 加强一下事件循环机制就好了
let Promise = require('./promise.js')
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('value')
}, 1000);
})
p.then((success) => {
console.log(success);
}, (err) => {
})
参考视频源码链接 https://www.bilibili.com/video/BV1LE411G7mS?p=2
|