其他分享
首页 > 其他分享> > 手写promise

手写promise

作者:互联网

自己实现promise功能

const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
function Promise(executor) {
    var _this = this
    this.state = PENDING; //状态
    this.value = undefined; //成功结果
    this.reason = undefined; //失败原因

    this.callback ={};
    function resolve(value) {
        if(_this.state === PENDING){
            _this.state = FULFILLED
            _this.value = value
            if(_this.callback.onFulfilled){
                _this.callback.onFulfilled(value)
            }
        }
    }
    function reject(reason) {
        if(_this.state === PENDING){
            _this.state = REJECTED
            _this.reason = reason
           if(_this.callback.onRejected){
            _this.callback.onRejected(value)
           }
        }
    }
    try {
        executor(resolve, reject);
    } catch (e) {
        reject(e);
    }
}
Promise.prototype.then = function (onFulfilled, onRejected) {
    if(this.state === FULFILLED){
        onFulfilled(this.value)
    }
    if(this.state === REJECTED){
        onRejected(this.reason)
    }
    if(this.state === PENDING){
        this.callback ={onFulfilled,onRejected} 
    }
};
<script src="promise.js"></script>
<script>
    let p=new Promise((resolve,reject)=>{
        setTimeout(() => {
            resolve('ok');
        }, 100);
        
    });
    p.then(value=>{
        console.log(value);
    },reason=>{
        console.log(reason);
    });
</script>

 

标签:state,value,onFulfilled,callback,reason,promise,手写,PENDING
来源: https://blog.csdn.net/yaobo2816/article/details/117042446