const PENDING = 'pending'
const FUFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
constructor (executor) {
executor(this.resolve, this.reject)
}
status = PENDING
value = undefined
reason = undefined
successCallback = []
failCallback = []
resolve = value => {
if (this.status !== PENDING) return
this.status = FUFILLED
this.value = value
while(this.successCallback.length) this.successCallback.shift()(this.value)
}
reject = reason => {
if (this.status !== PENDING) return
this.status = REJECTED
this.reason = reason
while(this.failCallback.length) this.failCallback.shift()(this.reason)
}
then(successCallback, failCallback) {
const promise2 = new MyPromise((resolve, reject) => {
if (this.status === FUFILLED) {
const successValue = successCallback(this.value)
resolvePromise(successValue, resolve, reject)
} else if (this.status === REJECTED) {
failCallback(this.reason)
} else {
this.successCallback.push(successCallback)
this.failCallback.push(failCallback)
}
})
return promise2
}
}
function resolvePromise(successValue, resolve, reject) {
if (successValue instanceof MyPromise) {
successValue.then(value => resolve(value), reason => reject(reason))
} else {
resolve(successValue)
}
}
const mypromise = new MyPromise((resolve, reject) => {
resolve('successValue')
})
function other () {
return new MyPromise((resolve, reject) => {
resolve('other')
})
}
mypromise.then(
values => {
console.log(values)
return 100
},
reason => {
console.log(reason)
}
)
.then(
values => {
console.log(values)
return other()
},
reason => {
console.log(reason)
}
)
.then(
values => {
console.log(values)
},
reason => {
console.log(reason)
}
)