(function (window) {
function Promise(excutor) {
this.status = "pending"
this.data = undefined
this.callbacks = []
const that = this
function resolve(value) {
if (that.status !== 'pending') return false
that.status = 'resolved'
that.data = value
if (that.callbacks.length > 0) {
setTimeout(() => {
that.callbacks.forEach(callbacksObj => {
callbacksObj.onResolved(that.data)
});
});
}
}
function reject(reason) {
if (that.status !== 'pending') return false
that.status = 'rejected'
that.data = reason
if (that.callbacks.length > 0) {
setTimeout(() => {
that.callbacks.forEach(callbacksObj => {
callbacksObj.onRejected(that.data)
});
});
}
}
try {
excutor(resolve, reject)
} catch (error) {
reject(error)
}
}
Promise.prototype.then = function (onResolved, onRejected) {
onResolved=typeof onRejected==="function"?onRejected:value=>value
onRejected=typeof onRejected==="function"?onRejected:reason=>{throw reason}
let that=this
return new Promise((resolve, reject) => {
function handle(callback) {
try {
let res=callback(that.data)
if (res instanceof Promise) {
res.then(resolve, reject)
} else {
resolve(res)
}
} catch (error) {
reject(error)
}
}
if (that.status === "pending") {
that.callbacks.push({
onResolved(value){
handle(onResolved)
},
onRejected(reason){
handle(onRejected)
}
})
} else if (that.status === "resolved") {
setTimeout(() => {
handle(onResolved)
});
} else {
setTimeout(() => {
handle(onRejected)
});
}
})
}
Promise.prototype.catch = function (onRejected) {
return this.then(undefined,onRejected)
}
Promise.resolve = function (value) {
new Promise((resolve, reject) => {
resolve(value)
})
}
Promise.rejected = function (reason) {
}
Promise.all = function (promises) {
}
Promise.race = function (promises) {
}
window.Promise = Promise
})(window)