三种状态 pending || resolved || rejected
当处于pending状态的时候,可以转移到resolved或者rejected状态
当处于resolved状态或者rejected状态的时候,就不可变
必须有一个then异步执行方法,then接收2个参数并且必须返回一个promise:
onResolved 用来接收promise成功的值
onRejected 用语接收promise失败的原因
promise.prototype.then = function(onResolved,onRejected){}
function myPromise(callback) {
this.status = 'pending'
this.successArray = [];
this.failArray = [];
let resolve = (value) => {
this.status = 'resolved';
this.successArray.forEach(fn => value = fn(value))
this.successArray = [];
this.value = value;
}
let reject = (value) => {
this.status = 'resolved';
this.failArray.forEach(fn => value = fn(value))
this.failArray = [];
this.value = value;
}
try {
callback(resolve, reject);
} catch (e) {
reject(e);
}
}
myPromise.prototype.then = function (success, fail) {
if (this.status === 'pending') {
success && this.successArray.push(success);
fail && this.failArray.push(fail);
} else if (this.status === 'resolved') {
success && success(this.value)
} else {
fail && fail(this.value);
}
return this;
}