老师catch和then的第二个参数处理是不是有问题啊?

来源:8-20 手写 Promise-then 的链式调用

weixin_慕丝2377090

2021-10-21

因为catch和then的第二个参数,是处理rejected状态的,但是它默认返回的应该是resolved啊。老师这里reject(newReason);不是又返回rejected的状态吗?
还有如果老师我这样理解是对的话pending里面该怎么改呢?

    then(fn1, fn2) {
        // 判断fn1, fn2是不是函数
        fn1 = typeof fn1 === 'function' ? fn1 : (v) => v;
        fn2 = typeof fn2 === 'function' ? fn2 : (e) => e;

        if (this.state === 'pending') {
            // 当pending状态下,fn1和fn2会存储到callbacks中
            return new MyPromise((resolve, reject) => {
                this.resolveCallbacks.push(() => {
                    try {
                        const newValue = fn1(this.value);
                        resolve(newValue);
                    } catch (error) {
                        reject(error);
                    }
                })
                this.rejectCallbacks.push(() => {
                    try {
                        const newReason = fn2(this.reason);
                        reject(newReason);
                    } catch (error) {
                        reject(error);
                    }
                })
            })
        }

        if (this.state === 'fulfilled') {
            // 要返回新的promise,传入当前的value,计算出新的value,resolve
            return new MyPromise((resolve, reject) => {
                try {
                    const newValue = fn1(this.value);
                    resolve(newValue);
                } catch (error) {
                    reject(error);
                }
            })
        }

        if (this.state === 'rejected') {
            // 要返回新的promise,传入当前的reason,生成新的reason,reject
            return new MyPromise((resolve, reject) => {
                try {
                    const newValue = fn2(this.reason);
                    resolve(newValue);  **//这里改为resolve**
                } catch (error) {
                    reject(error);
                }
            })
        }
    }
    // 就是then的语法糖 
    catch(fn) {
        return this.then(null, fn);
    }
写回答

2回答

笑着拍拍你的头

2022-04-19

1.把then里fn2判断改成fn2 = typeof fn2 === 'function' ? fn2 : (reason) => { throw reason }
2.把then里state = 'pending'里rejectCallbacks的reject改成resolve(newReason)
3.把then里state = 'rejected'里的reject改成resolve(newReason)


2
0

双越

2021-10-22

把这里的 reject 替换为 resolve 即可

//img.mukewang.com/szimg/61720af309ed1b0f11521040.jpg

2
3
笑着拍拍你的头
回复
慕移动5643659
1.把then里fn2判断改成fn2 = typeof fn2 === 'function' ? fn2 : (reason) => { throw reason } 2.把then里state = 'pending'里rejectCallbacks的reject改成resolve(newReason) 3.把then里state = 'rejected'里的reject改成resolve(newReason)
2022-04-19
共3条回复

一天时间高效准备前端技术一面 匹配大厂面试要求

针对时下面试高频考点,帮助新人js面试快速通关

4694 学习 · 1681 问题

查看课程