function myPromise(executor) {
let that = this
this.status = 'pending'
this.success = undefined
this.error = undefined
this.successCallBack = []
this.errorCallBack = []
function resolve(value) {
if (that.status !== 'pending') return;
that.status = 'fulfilled'
that.success = value
while (that.successCallBack.length)
that.successCallBack.shift()(that.success)
}
function reject(err) {
if (that.status !== 'pending') return;
that.status = 'rejected'
that.error = err
while (that.errorCallBack.length)
that.errorCallBack.shift()(err)
}
try {
executor(resolve, reject)
} catch (err) {
reject(err)
}
}
myPromise.prototype.then = function (resolve, reject) {
let that = this
let pro = new myPromise((resolve1, reject1) => {
if (that.status === 'pending') {
this.successCallBack.push(() => {
let val = resolve(that.success)
resolve1(val)
})
this.errorCallBack.push(() => {
let err = reject(that.error)
reject1(err)
})
}
else if (that.status === 'fulfilled') {
let val = resolve(that.success)
resolve1(val)
}
else {
let err = reject(that.error)
reject1(err)
}
})
return pro
}
let p1 = new myPromise((resolve, reject) => {
resolve('123')
})
console.log(p1)
p1.then(function (value) {
console.log('第一个成功回调')
}, function () { })
.then(function () {
console.log('第二个成功回调')
}, function () { })
.then(function () {},
function () { console.log('第三个成功回调') })
console