对Promise的实现

84 阅读1分钟
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.
// == 基础原理实现 ==
// Promise类,原型
let p = new Promise(functino(resovle, reject){
    // 默认执行, 状态pending
    console.log('run init');
    // 切换状态执行 resolved | rejected
    // 状态从pending切换时,只会执行一次有效的切换,即第一次改变结果有效
    resolve('this is resovle');
    reject('this is reject');
});
p.prototype.then((value)=>{
    console.log('then resovle()', value);
},(reason)=>{
    console.log('then reject()', reason);
});
// 过程:
// 实例化Promise后,调用executor方法
// executor中两个参数(成功时调用的resolve(value), 失败时调用的reject(reason))
// 两个函数的作用,改变默认状态,赋值函数参数
// then()回调中根据当前状态触发成功onFulfilled(value)或失败onRejected(reason)
// 实现:
function Promise(executor){
    // resolve()方法中,this指向方法内部,需要外部定义
    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);
    }
}

// == 异步订阅待更新 ==