【js】what is Promise和手写实现简易版Promise

什么是Promise

官方的解释:Promise是一个用来传递异步操作消息的对象。
Promise有三种状态,pending(等待中),resolved(已完成),rejected(已失败)。对象状态不受外界影响,只有异步操作的结果可以改变状态,这就是“promise“的由来

怎么用Promise

Promise接受一个函数作为参数,这个参数函数的两个参数分别是resolved和rejected,用来执行了两种状态的回调函数。
当Promise实例生成后,用then方法来指定两种状态的回调函数。举一个简单例子

//axios是一个基于Promise的http请求,可以直接调用then

this.axios.get(url).then((res)=>{
        //请求成功 resolved的回调
    },(err)=>{
        //请求失败 rejected的回调
    })
})

将多个Promise封装成一个

假如你需要等待多个Promise请求resoved后在执行,可以调用Promise.all()
这个api接受一个promise实例数组做参数。

手动实现Promise

//1.定义三种状态
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
function MyPromisr(fn){
       //重命名this,防止接下来找不到正确的this
       const that = this
       that.state = PENDING //初始状态为等待
       that.value = null //value用于保存resolved或rejoiced传入的值
       that.resolvedCallbacks = [] //成功请求后的回调数组
       //定义完成的回调函数
       function resolved(value) {
            // 只有在等待状态才可以改变状态
            if (that.state === PENDING) {
                that.state = RESOLVED
                that.value = value
                that.resolvedCallbacks.map(cb => cb(that.value))
            }
        }
        //定义拒绝的回调函数
        function rejected(value) {
            // 只有在等待状态才可以改变状态
            if (that.state === PENDING) {
                that.state = REJECTED
                that.value = value
                that.rejectedCallbacks.map(cb => cb(that.value))
            }
        }
        // 定义了两种状态的回调函数后,执行mypromise传参的函数
        try {
            fn(resolved,rejected)
        } catch (e) {
            rejected(e)
        }
}
// 定义then
MyPromise.prototype.then = function(onFulfilled,onRejected){
    const that = this
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled :v => v
    onRejected = 
     typeof onRejected === 'function'
        ? onRejected
        : r => {
            throw r
        }
    if (that.state === PENDING) {
        that.resolvedCallbacks.push(onFulfilled)
        that.rejectedCallbacks.push(onRejected)
    }
    if (that.state === RESOLVED) {
        onFulfilled(that.value)
    }
    // console.log(that.state,'has change')
    if (that.state === REJECTED) {
        onRejected(that.value)
    }
}

//调用
new MyPromise((resolved,rejected) => {
    setTimeout(()=>{
        resolved(1)
        rejected(2)
    },0)
}).then(value=>{
    console.log(value)
},value=>{
    console.log(value)
})

评论

暂无评论