var MyPromise = function (fn) {
this.PromiseState = 'pending'
this.PromiseResult = undefined
this.thenCallback = undefined;
this.catchCallback = undefined;
var _this = this;
var resolve = function (value) {
if (_this.PromiseState === 'pending') {
_this.PromiseState = 'fulfilled';
_this.PromiseResult = value
if (value instanceof MyPromise) {
value.then((res)=>{
if (_this.thenCallback) {
_this.thenCallback(res)
}
})
} else {
setTimeout(() => {
if (_this.thenCallback) {
_this.thenCallback(value)
}
})
}
}
}
var reject = function (errValue) {
if (_this.PromiseState === 'pending') {
_this.PromiseState = 'rejected';
_this.PromiseResult = errValue;
setTimeout(() => {
if (_this.catchCallback) {
_this.catchCallback(errValue)
} else if (_this.thenCallback) {
_this.thenCallback(errValue)
} else{
throw('catch is no defined')
}
})
}
}
if (fn) {
fn(resolve, reject)
}
}
MyPromise.prototype.then = function (callback) {
var _this = this;
return new MyPromise((resolve, reject) => {
_this.thenCallback = (value) => {
if (_this.PromiseState === 'rejected') {
reject(value)
} else {
var lastcallback = callback(value)
if (lastcallback instanceof MyPromise && lastcallback.PromiseState === 'rejected') {
lastcallback.catch((errValue) => {
reject(errValue)
})
} else {
resolve(lastcallback)
}
console.log(lastcallback);
}
}
})
}
MyPromise.prototype.catch = function (callback) {
var _this = this;
return new MyPromise((resolve, reject) => {
_this.catchCallback = (err) => {
var lastcallback = callback(err)
resolve(lastcallback)
}
})
}
MyPromise.resolve=(res)=>{
return new MyPromise((resolve,reject)=>{
resolve(res)
})
}
MyPromise.reject=(res)=>{
return new MyPromise((resolve,reject)=>{
reject(res)
})
}