Terminology“promise” is an object or function with a then method whose behavior conforms to this specification.“thenable” is an object or function that defines a then method.“value” is any legal JavaScript value (including undefined, a thenable, or a promise).“exception” is a value that is thrown using the throw statement.“reason” is a value that indicates why a promise was rejected.
RequirementsPromise StatesA promise must be in one of three states: pending, fulfilled, or rejected.When pending, a promise:may transition to either the fulfilled or rejected state.When fulfilled, a promise:must not transition to any other state.must have a value, which must not change.When rejected, a promise:must not transition to any other state.must have a reason, which must not change.Here, “must not change” means immutable identity (i.e. ===), but does not imply deep immutability.
let p = new Promise(functino(resovle, reject){
console.log('run init');
resolve('this is resovle');
reject('this is reject');
});
p.prototype.then((value)=>{
console.log('then resovle()', value);
},(reason)=>{
console.log('then reject()', reason);
});
function Promise(executor){
let self = this;
self.status = 'pending';
self.value = undefined;
self.reason = undefined;
executor(resolve, reject);
function resolve(value){
if(self.status === 'pending'){
self.stauts = 'fulfilled';
self.value = value;
}
}
function reject(reason){
if(self.stauts ==== 'pending'){
self.stauts = 'rejected;
self.reason = reason;
}
}
}
Promise.prototype.then = function(onFulfilled, onRejected){
if(this.status === 'fulfilled'){
onFulfilled(this.value);
}
if(this.stauts ==== 'rejected'){
onRejected(this.reason);
}
}
// == 异步订阅待更新 ==