function MyPromise(executor) {
let that = this
this.status = 'pending'
this.data = undefined
this.onResolveCallback = []
this.onRejectCallback = []
function resolve(data) {
setTimeout(() => {
if (that.status === 'pending') {
that.status = 'resolved'
that.data = data
for (let callback of that.onResolveCallback) {
callback(data)
}
}
})
}
function reject(data) {
setTimeout(() => {
if (that.status === 'pending') {
that.status = 'rejected'
that.data = data
for (let callback of that.onRejectCallback) {
callback(data)
}
}
})
}
try {
executor(resolve, reject)
} catch (error) {
reject(error)
}
}
MyPromise.prototype.then = function (onResolved, onRejected) {
let that = this
onResolved = typeof onResolved === 'function' ? onResolved : function (v) { return v }
onRejected = typeof onRejected === 'function' ? onRejected : function (v) { return v }
if (that.status === 'resolved') {
return new Promise(function (resolve, reject) {
setTimeout(() => {
try {
let res = onResolved(that.data)
if (res instanceof MyPromise) {
res.then(resolve, reject)
} else {
resolve(res)
}
} catch (error) {
reject(error)
}
})
})
}
if (that.status === 'rejected') {
return new Promise(function (resolve, reject) {
setTimeout(() => {
try {
let res = onResolved(that.data)
if (res instanceof MyPromise) {
res.then(resolve, reject)
} else {
reject(res)
}
} catch (error) {
reject(error)
}
})
})
}
if (that.status === 'pending') {
return new Promise(function (resolve, reject) {
that.onResolveCallback.push(function () {
try {
let res = onResolved(that.data)
if (res instanceof MyPromise) {
res.then(resolve, reject)
} else {
resolve(res)
}
} catch (error) {
reject(error)
}
})
that.onRejectCallback.push(function () {
try {
let res = onRejected(that.data)
if (res instanceof MyPromise) {
res.then(resolve, reject)
} else {
reject(res)
}
} catch (error) {
reject(error)
}
})
})
}
}
MyPromise.prototype.catch = function (reject) {
this.then(null, reject)
}
console