用es6实现一个简单的promise

promise是一个面试经常会问的问题,在这里我们可以通过es6的语法实现一个简单的promise,面试能写出来基本就没问题了

const PENDING = 'pending';
const RESOLVED = 'resolved';
const REJECTED = 'rejected';

class MyPromise {
    constructor(fn) {
        this.state = PENDING;
        this.value = null; //保存resolve或reject中传入的值
        this.resolvedCallBacks = [];
        this.rejectedCallbacks = [];
        this.resolve = this.resolve.bind(this);
        this.reject = this.reject.bind(this);
        //执行fn函数
        try {
            fn(this.resolve, this.reject); //执行函数之后,将回调函数传入
        } catch (e) {
            this.reject(e);
        }
    }

    resolve(value) {
        //只有等待状态才能更改状态
        if (this.state === PENDING) {
            this.state = RESOLVED;
            this.value = value;
            //把存在调用栈里的then方法中的回调函数调用一下
            this.resolvedCallBacks.map((cb) => cb(this.value));
        }
    }

    reject(value) {
        if (this.state === PENDING) {
            this.state = REJECTED;
            this.value = value;
            this.rejectedCallbacks.map((cb) => cb(this.value));
        }
    }

    then(onFulfilled, onRejected) {
        //确保都转化为函数
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (v) => v;
        onRejected = typeof onRejected === 'function' ? onRejected : (err) => {
            throw err
        };
        switch (this.state) {
            case PENDING:
                this.resolvedCallBacks.push(onFulfilled);
                this.rejectedCallbacks.push(onRejected);
                break;
            case RESOLVED:
                //执行回调函数
                onFulfilled(this.value);
                break;
            case REJECTED:
                onRejected(this.value);
                break;
            default:
                throw 'unknown state';

        }
    }
}

const promise = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('hello world')
    }, 100)
});

promise.then((value) => {
    console.log(value)
});




当然这只是一种很简单的实现方法,一些链式调用等高级应用还没有实现。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值