function Promise(executor) {
this.status = 'pending';
this.data = '';
this.reason = '';
this.fn1CallBacks = [];
this.fn2CallBacks = [];
let resolve = value => {
if (this.status === 'pending') {
this.status = 'fulfilled';
this.data = value;
for (var i = 0; i < this.fn1CallBacks.length; i++) {
self.fn1CallBacks[i](value)
}
}
};
let reject = reason => {
if (this.status === 'pending') {
this.status = 'reject';
this.reason = reason;
for (var i = 0; i < this.fn2CallBacks.length; i++) {
self.fn2CallBacks[i](reason)
}
}
};
try {
executor(resolve,reject)
} catch (err) {
reject(err)
}
}
Promise.prototype.then = function(fn1,fn2) {
var self = this;
var promise2;
fn1 = type fn1 === 'function' ? fn1 : function(v) {};
fn2 = type fn2 === 'function' ? fn2 : function(r) {};
if (self.status === 'resolved') {
return promise2 = new Promise(function(resolve,reject) {
try {
var x = fn1(self.data);
resolve(x)
} catch(err) {
reject(err)
}
})
}
if (self.status === 'reject') {
return promise2 = new Promise(function(resolve,reject) {
try {
var x = fn2(self.data);
reject(x)
} catch(err) {
reject(err)
}
})
}
if (self.status === 'pending') {
return promise2 = new Promise(function(resolve,reject) {
this.fn1CallBacks.push(function(value) {
try {
var x = fn1(self.data);
resolve(x)
} catch(err) {
reject(err)
}
})
this.fn2CallBacks.push(function(value) {
try {
var x = fn2(self.data);
reject(x)
} catch(err) {
reject(err)
}
})
})
}
}