function MyPromise(executor) {
this.value = null
this.state = 'pending'
this.resolveQueue = []
this.rejectQueue = []
var _this = this
function resolve(value) {
if(value instanceof MyPromise) {
return value.then(resolve, reject)
}
setTimeout(function() {
if(_this.state === 'pending') {
_this.state = 'resolved'
_this.value = value
_this.resolveQueue.forEach(function(cb) { cb(value) })
}
}, 0)
}
function reject(value) {
setTimeout(function() {
if(_this.state === 'pending') {
_this.state = 'rejected'
_this.value = value
_this.rejectQueue.forEach(function(cb) { cb(value) })
}
}, 0)
}
executor(resolve, reject)
}
MyPromise.prototype = {
then(onFulfilled, onRejected) {
if(this.state === 'pending') {
this.resolveQueue.push(onFulfilled)
this.rejectQueue.push(onRejected)
}
if(this.state === 'resolved') {
onFulfilled(this.value)
}
if(this.state === 'rejected') {
onRejected(this.value)
}
return this
}
}
网友评论