手写Promsie

手写Promsie

代码
index.js


const MyPromise = require('./Promsie.js')

// what why how 
// 三种状态:等待态 pedding  成功态fullfilled  失败态 rejected  

// 最终一种状态:成功/失败

const p = new MyPromise(function (resolve, reject) {
     setTimeout(function () {
         resolve(1)
     },1000)
     
})
p.then(function(data) {
    console.log(data);
}, function (err) {
    console.log(err);
})

Promsie.js
代码


const PEDDING = 'PEDDING'; // 等待  
const FULLFILLED = 'FULLFILLED'; // 成功
const ONREJECTED = 'ONREJECTED'  // 失败
class Promise {
    // 构造函数
    constructor (executor) {
        this.status = PEDDING; // 默认等待
        this.value = undefined; // 成功的值
        this.reason = undefined; // 失败的值
        // 成功回调队列
        this.onFullfilledCallBacks = [];
        // 失败回调队列
        this.onRejectedCallBacks = [];
        // 成功
        const resolve = (value)=>{
            if (this.status === PEDDING) {
                // 变成成功态
                this.status = FULLFILLED;
                this.value = value;
                this.onFullfilledCallBacks.forEach(fn=>fn())
            }
        }

        // 失败
        const reject = (reason) =>{
            if (this.status === PEDDING ) {
                this.status = ONREJECTED;
                this.reason = reason;
                this.onRejectedCallBacks.forEach(fn=>fn())
            }
        }

        executor(resolve,reject)
    }
    then (onFullfilled, onRejected) {

        // 成功
        if (this.status === FULLFILLED) {
            onFullfilled(this.value)
        }

        // 失败
        if (this.status === ONREJECTED ) {
            onRejected(this.reason)
        }

        // 等待
        if (this.status === PEDDING) {
            // 成功
            this.onFullfilledCallBacks.push(()=>{
                onFullfilled(this.value)
            })

            // 失败
            this.onRejectedCallBacks.push(()=>{
                onRejected(this.reason)
            })
        }

    }
}

// const p = new Promise()

module.exports = Promise;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值