手写一个promise函数,实现then 的链式调用和值的穿透特性

第一步来了解一下promise的基本特性;

1、promise 有三个状态:pendingfulfilled,or rejected

2、new promise时, 需要传递一个executor()执行器,接受两个参数,分别是resolvereject,并执行器立即执行;

3、promise 的默认状态是 pending;

4、promise 有一个value保存状态的值,成功或失败;

5、promise 只能从pendingrejected, 或者从pendingfulfilled,状态一旦确认,就不会再改变;

6、promise 必须有一个then方法,then 接收两个参数,分别是 promise 成功的回调 onFulfilled, 和 promise 失败的回调 onRejected,参数都是value;

7、如果then中抛出异常,那么就会把这个异常作为参数,传递给下一个 then 的失败的回调onRejected,如果没有这个回调函数,则到catch方法中;

写一个简单的promise

const p1 = new Promise((resolve, reject) => {
  console.log('create a promise');
  setTimeout(() => {
        resolve('成功了');
  }, 3000)
})

p1.then(data => {
  console.log(data)
})

//输出
create a promise
成功了

实现代码如下

class promise {
    constructor(executor) {
        //三种状态
        this.statusArr = ['pending', 'fulfilled', 'rejected'];
        this.status = 'pending';
        //存一个值;默认undefined
        this.result = void 0;
        if (typeof executor === 'function') {
            //
            this.resolve = (res) => {
                this.status = 'fulfilled';
                if (this.await_fn) {
                    this.await_fn(res)
                } else {
                    this.result = res;
                }
            };
            //由于resolve是一个微任务;改为 添加setTimeout
            this.resolve = (res) => {
                setTimeout(() => {
                    this.status = 'fulfilled';
                    if (this.await_fn) {
                        this.await_fn(res)
                    } else {
                        this.result = res;
                    }
                }, 0)
            };
            this.reject = (res) => {
                this.status = 'rejected';
                if (this.catch_fn) {
                    this.catch_fn(res)
                } else {
                    this.result = res;
                }
            };
            executor(this.resolve, this.reject);

            this.then = (fn) => {
                if (this.status === 'fulfilled') {
                    fn(this.result)
                } else {
                    this.await_fn = fn;
                }
            }
            this.catch = (fn) => {
                if (this.status === 'rejected') {
                    fn(this.result)
                } else {
                    this.catch_fn = fn;
                }
            }

        } else {
            console.error(`${executor} should be a function`)
        }
    }
}

const p1 = new promise((res, rej) => {
    console.log('create a promise')
    se
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值