// 实现一个简易版的promise
//先创建三个常量用于表示状态
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
function MyPromise(fn) {
const that = this
that.state = PENDING //一开始Promise转态应该是pedding
that.value = null //value用于保存resolved或者rejected传入的值
//以下两个属性用于保存then中的回调,因为当执行完Promise时转态可能还在pending状态中,这时候应该把then中的回调保存起来用于状态改变时使用
that.resolvedCallbacks = []
that.rejectedCallbacks = []
function resolved(value) {
if(that.state === PENDING){
that.state = RESOLVED
that.value = value
that.resolvedCallbacks.map(cb => cb(that.value))
}
}
function rejected(value) {
if(that.state === REJECTED){
that.state = REJECTED
that.value = value
that.rejectedCallbacks.map(cb => cb(that.value))
}
}
try {
fn(resolved,rejected)
} catch (e) {
rejected(e)
}
}
//实现then函数
MyPromise.prototype.then = function(onFullfied,onRejected) {
const that = this
onFullfied = typeof onFullfied === 'function'?onFullfied:v=>v
onRejected = typeof onRejected === 'function'?onRejected:r=>{
throw r
}
if(that.state === PENDING){
that.resolvedCallbacks.push(onFullfied)
that.rejectedCallbacks.push(onRejected)
}
if(that.state === RESOLVED){
onFullfied(that.value)
}
if(that.state === REJECTED){
onRejected(that.value)
}
}
new MyPromise((resolved,rejected)=>{
setTimeout(()=>{
resolved(1)
},0)
}).then(value=>{
console.log(value); // 1
})