function Promize (executor) {
return new _Promize (executor)
}
function _Promize (executor) {
this.STATUS = {
PENDING: 'Pending', // 等待态
FULFILLED: 'Fulfilled', // 执行态
REJECTED: 'Rejected' // 拒绝态
}
this.status = this.STATUS.PENDING
this.thenQueue = []
this.catchExecutor = null
// 保证链式操作以后才执行
setTimeout(() => {
try {
executor(this.resolve.bind(this), this.reject.bind(this))
} catch (err) {
this.reject.call(this, err)
}
},0)
}
_Promize.prototype.resolve = function (data) {
if (this.status === this.STATUS.PENDING) {
this.stauts = this.STATUS.FULFILLED
let thenTask = this.thenQueue.shift()
if (thenTask) {
this.callbackData = data
thenTask()
}
}
}
_Promize.prototype.reject = function (err) {
if (this.catchExecutor) {
this.catchExecutor(err)
}
}
_Promize.prototype.catch = function (errorExecutor) {
this.catchExecutor = errorExecutor
return this
}
_Promize.prototype.then = function (task) {
this.thenQueue.push(() => {
let res = task(this.callbackData)
if (res) {
this.callbackData = res
}
this.next()
})
// 链式调用
return this
}
_Promize.prototype.next = function () {
if (this.thenQueue.length > 0) {
let thenTask = this.thenQueue.shift()
thenTask()
}
}
Promize(function(resolve, reject){
setTimeout(() => {
console.log('done')
throw new Error('hi')
resolve('123')
},2000)
}).then((data) => data+'2')
.then((data) => console.log(data))
.catch((err) => console.log('err:'+ err))
console