手写简单Promise

/**
 * promise 使用方法
 * promise 入参函数a,函数a的入参b,c 分别对应resolve函数和rejecte函数
 * a().then(res=>{},err=>{})
*/

function MyPromise(fn){
    var _this = this
    _this.state = 'pendding' // promise 初始状态pendding
    _this.value = undefined  // 成功的结果 ,执行resolve(value)时候,promise 状态变为resolved,并将传递过来的value 赋值给 _this.value
    _this.reason = undefined // 失败的原因, 执行reject(reason)时候, promise 状态变为resolved,并将传递过来的reason 赋值给 _this.reason
    function resolve(value){
        // 执行resolve函数时时候 ,把promise初始的pendding状态 变成 resolved
        if(_this.state === "pendding"){
            _this.state = 'resolved'
            _this.value =  value
        }
    }
    function rejecte(reason){
        // 执行resolve函数时时候 ,把promise初始的pendding状态 变成 resolved
        if(_this.state === "pendding"){
            _this.state = 'rejected'
            _this.reason =  reason
        }
    }

    try{
        // 至于fn里面是执行resolve 还是reject 具体看情况了
        fn(resolve,rejecte)
    }catch(err){
        rejecte()
    }
}

MyPromise.prototype.then = function(resolve,reject){
    if(this.state === 'resolved' && typeof resolve === "function"){
        // 将this.value 传递给resolve函数
        resolve(this.value)
    }
    if(this.state === 'rejected' && typeof reject === "function"){
        // 将this.reason 传递给reject函数
        reject(this.reason)
    }
}

// 自此最简单的promise 封装完成
let a = new MyPromise((resolve,reject)=>{
    console.log('promise Begin')
    reject('heiheihei=> error ')
})
a.then(res=>{
    console.log('res',res)
},err=>{
    console.log(err,'err')
})

问题,如果a Promise对象中setTimeout 执行reject会怎样?
代码如下:

let a = new MyPromise((resolve,reject)=>{
    console.log('promise Begin')
    setTimeout(()=>{
        reject('12138')
    },2000)
    
})

此时的reject函数2s之后才执行,promise状态2s之后才变为rejected?

tip:当then里面函数运行时,resolve/reject由于是异步setTImeout执行的,还没有来得及修改state,此时还是PENDING状态;因此我们需要对异步的情况做一下处理。

异步setTimeout中执行的resolve,是因为放在事件队列里面,而promise状态处理函数是同步的,所以导致后来异步的resolve调用不了promise.then(resolve,reject)中的resolve??

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值