const PENDING = 'PENDING'
const RESOLVED = 'RESOLVED'
const REJECTED = 'REJECTED'
function Promise(fn) {
let seft = this
seft.status = PENDING
seft.value = null
seft.resolvedCallbacks = []
seft.rejectedCallbacks = []
function r(value) {
//成功
if (value instanceof Promise) {
return value.then(r, j)
}
setTimeout(() => {
if (seft.status === PENDING) {
seft.status = RESOLVED
seft.value = value
seft.resolvedCallbacks.forEach(callback => {
callback(value)
})
}
}, 0);
}
function j(value) {
//失败
setTimeout(() => {
if (seft.status === PENDING) {
seft.status = REJECTED
seft.value = value
seft.resolvedCallbacks.forEach(callback => {
callback(value)
})
}
}, 0);
}
try {
fn(r, j)
} catch (e) {
j(e)
}
}
Promise.prototype.then = function (onResolved, onRejected) {
onResolved = typeof (onResolved) === 'function' ? onResolved : function (value) {
return value
}
onRejected = typeof (onRejected) === 'function' ? onRejected : function (value) {
return value
}
if(this.status = PENDING){
this.resolvedCallbacks.push(onResolved)
this.rejectedCallbacks.push(onResolved)
}
if(this.status = RESOLVED){
onResolved(this.value)
}
if(this.status = REJECTED){
onRejected(this.value)
}
}