思路
未添加异步处理等其他边界情况 ①自动执行函数,②三个状态,③then
class Promise {
constructor(fn) {
// 添加三个状态
this.state = 'pending'
this.value = undefined
this.reason = undefined
let resolve = value => {
if (this.state === 'pending') {
this.state = 'fulfilled'
this.value = value
}
}
let reject = value => {
if (this.state === 'pending') {
this.state = 'rejected'
this.value = value
}
}
try {
fn(resolve, reject)
} catch (e) {
reject(e)
}
}
then(onFullfilled, onRejected) {
switch (this.state) {
case "fulfilled":
onFullfilled()
break
case "rejected":
onRejected()
break
default :
}
}
}