从零手写Promise——then的链式调用

上一节一步步实现了一个Promise的基本功能,先回顾一下上节的代码

function changePromiseStatus(tar, key, value) {
    if(tar.status === "pending") {
        tar[key] = value;
        // 如果key为value代码是fulfilled,如果key是reason是rejected
        if(key === 'value') {
            tar.status = "fulfilled";
            // 开始执行搜集的方法
            tar.resolveCallbacks.forEach(fn => fn());
        } else {
            tar.status = "rejected";
            // 开始执行搜集的方法
            tar.rejectCallbacks.forEach(fn => fn());
        }
    }
}

class MyPromise {
    status = "pending"; // 状态
    value = undefined;  // 使用resove时记录的值
    reason = undefined; // 使用reject时记录的出错原因
    resolveCallbacks = []; // 用来收集状态为fulfilled时的执行方法
    rejectCallbacks = []; // 用来收集状态rejected时的执行方法

    constructor(executor) {
        // 创建resolve方法
        const resolve = res => {
            changePromiseStatus(this, 'value', res);            
        }
        // 创建reject方法
        const reject = err => {
            changePromiseStatus(this, 'reason', err);         
        }
        // 尝试执行executor,并将resolve,reject作为实参传给外部使用
        // 如果创建实例时没有传executor方法时则直接报错,走reject
        try {
            executor(resolve, reject);
        } catch(err) {
            reject(err);
        }
    }

    then(onFulfilled, onRejected) {
        switch(this.status) {
            case "fulfilled":
                onFulfilled(this.value);
                break;
            case "rejected":
                onRejected(this.reason);
                break;
            case "pending": {
                // 当状态为pending时收集待执行的方法
                this.resolveCallbacks.push(() => onFulfilled(this.value)); // 为了便于传参在外层包裹了一次方法              
                this.rejectCallbacks.push(() => onRejected(this.reason));
            }
        }
    }
}

但是光只实现基本功能还不行,因为使用Promise的原因很大程度上是为了避免回调函数嵌套太多产生回调地狱,先抛开async await不谈,Promise的链式调用在某一程序上大大避免了这种回调地狱的局面。如:

// 以jquery为例的ajax回调地狱
$.get("/getdata", res => {
    $.get("/getdata2", res2 => {
        $.get("/getdata3", res3 => {

        })
    })
})
// 链式调用
p.then(res => {
    console.log(res);
    return 400;
}).then(res => {
    console.log(res);
    return 300;
}).then(res => {
    console.log(res)
});

链式虽然看着还是有点不太舒服,但是已经比回调函数一层嵌一层看着舒服多了,接下来的内容就是开始实现这种链式调用了。

首先在写代码之前,先说明一下链式调用的特征:
1、要使then方法之后再使用then方法就得保证then方法里返回一个新的Promise对象
2、下一个then可以接收上一个then处理之后返回的结果
3、下一个then方法是要等待上一个then方法执行完之后才开始执行

根据以上特征下列就开始then方法的改造了,如下:

then(onFulfilled, onRejected) {
        // 需要返回一个新的promise对象
        return new MyPromise((resolve, reject) => {
            let x = null;
            switch(this.status) {
                case "fulfilled":
                    // 等待并获取当前执行的结果
                    x = onFulfilled(this.value);
                    // 将其结果传入下一次then
                    resolve(x);                
                    break;
                case "rejected":
                    x = onRejected(this.reason);
                    resolve(x);   
                    break;
                case "pending": {
                    // 当状态为pending时收集待执行的方法
                    this.resolveCallbacks.push(() => {
                        x = onFulfilled(this.value)
                        resolve(x);
                    }); // 为了便于值参在外层包裹了一次方法              
                    this.rejectCallbacks.push(() => {
                        x = onRejected(this.reason);
                        resolve(x);
                    });
                }
            }
        });
    }

接下来测试一下以下代码看能否按照预想打印出结果

// 使用
const p = new MyPromise((resolve, reject) => {
    resolve(500);
});

p.then(res => {
    console.log(res);
    return 400;
}).then(res => {
    console.log(res);
    return 300;
}).then(res => {
    console.log(res)
});

运行结果依次打印500 400 300,结果正确。
简单的链式调用已经完成,但是如果then方法中处理的有异步任务呢,如下:

p.then(res => {
    setTimeout(() => {
        console.log(res);
    }, 400);
    return 400;
}).then(res => {
    setTimeout(() => {
        console.log(res);
    }, 300);
    return 300;
}).then(res => {
    console.log(res)
});

结果为:300 400 500
这时就会结果虽然这几个值都打印出来了,但是顺序不符合我们的预期,预期的效果应该是上一次then执行完再执行下一次then,所以我们要的效果是500 400 300的结果。
既然处理过程是异步了,那我们将异步的过程使用promise包起来试试呢,如下:

p.then(res => {
    return new MyPromise((resolve, reject) => {
        console.log(res);
        resolve(400);
    });
}).then(res => {
    return new MyPromise((resolve, reject) => {
        console.log(res);
        resolve(300);
    });
}).then(res => {
    console.log(res)
});

理解很丰满,现实很骨感,运行结果如下:

image.png

顺序好像是对了,但是值又不对了,后面两次明显是一个promise对象,那看来还要对返回的结果做判断了,如果是一个promise对象,则自行then之后才把结果传给后面去,既然这样那这部分代码干脆就抽离用一个函数完成比较好。

// 处理then的处理结果
function handleThenResult(result, resolve, reject) {
    // 判断是否为MyPromise对象 
    // 如果是就将then之后的结果分别用resolve,reject传到后面的then中
    // 如果是一个普通的数据,则直接使用resolve传到后面then中
    if(result instanceof MyPromise) {
        // 便于理解的写法
        //result.then(res => resolve(res), err => reject(err))
        result.then(resolve, reject); // 上面代码精简后的写法,上面本质都是使用resolve,reject方法传值
    } else {
        resolve(result);
    }
}
then(onFulfilled, onRejected) {
        // 需要返回一个新的promise对象
        return new MyPromise((resolve, reject) => {
            let x = null;
            switch(this.status) {
                case "fulfilled":
                    // 等待并获取当前执行的结果
                    handleThenResult(onFulfilled(this.value), resolve, reject);
                    break;
                case "rejected":
                    handleThenResult(onRejected(this.reason), resolve, reject);
                    break;
                case "pending": {
                    // 当状态为pending时收集待执行的方法
                    this.resolveCallbacks.push(() => {
                        handleThenResult(onFulfilled(this.value), resolve, reject);
                    }); // 为了便于传参在外层包裹了一次方法              
                    this.rejectCallbacks.push(() => {
                        handleThenResult(onRejected(this.reason), resolve, reject);
                    });
                }
            }
        });
    }

此时再尝试运行如下代码

p.then(res => {
    return new MyPromise((resolve, reject) => {
        console.log(res);
        resolve(400);
    });
}).then(res => {
    return new MyPromise((resolve, reject) => {
        console.log(res);
        resolve(300);
    });
}).then(res => {
    console.log(res)
});

结果是依次等待并输出:500 400 300,已达到预期效果了,下面将完整的代码展示出来

// 处理promise对象实例状态改变的时候
function changePromiseStatus(tar, key, value) {
    if(tar.status === "pending") {
        tar[key] = value;
        // 如果key为value代码是fulfilled,如果key是reason是rejected
        if(key === 'value') {
            tar.status = "fulfilled";
            // 开始执行搜集的方法
            tar.resolveCallbacks.forEach(fn => fn());
        } else {
            tar.status = "rejected";
            // 开始执行搜集的方法
            tar.rejectCallbacks.forEach(fn => fn());
        }
    }
}

// 处理then的处理结果
function handleThenResult(result, resolve, reject) {
    // 判断是否为MyPromise对象 
    // 如果是就将then之后的结果分别用resolve,reject传到后面的then中
    // 如果是一个普通的数据,则直接使用resolve传到后面then中
    if(result instanceof MyPromise) {
        // 便于理解的写法
        //result.then(res => resolve(res), err => reject(err))
        result.then(resolve, reject); // 上面代码精简后的写法,上面本质都是使用resolve,reject方法传值
    } else {
        resolve(result);
    }
}

class MyPromise {
    status = "pending"; // 状态
    value = undefined;  // 使用resove时记录的值
    reason = undefined; // 使用reject时记录的出错原因
    resolveCallbacks = []; // 用来收集状态为fulfilled时的执行方法
    rejectCallbacks = []; // 用来收集状态rejected时的执行方法

    constructor(executor) {
        // 创建resolve方法
        const resolve = res => {
            changePromiseStatus(this, 'value', res);            
        }
        // 创建reject方法
        const reject = err => {
            changePromiseStatus(this, 'reason', err);         
        }
        // 尝试执行executor,并将resolve,reject作为实参传给外部使用
        // 如果创建实例时没有传executor方法时则直接报错,走reject
        try {
            executor(resolve, reject);
        } catch(err) {
            reject(err);
        }
    }

    then(onFulfilled, onRejected) {
        // 需要返回一个新的promise对象
        return new MyPromise((resolve, reject) => {
            let x = null;
            switch(this.status) {
                case "fulfilled":
                    // 等待并获取当前执行的结果
                    handleThenResult(onFulfilled(this.value), resolve, reject);
                    break;
                case "rejected":
                    handleThenResult(onRejected(this.reason), resolve, reject);
                    break;
                case "pending": {
                    // 当状态为pending时收集待执行的方法
                    this.resolveCallbacks.push(() => {
                        handleThenResult(onFulfilled(this.value), resolve, reject);
                    }); // 为了便于传参在外层包裹了一次方法              
                    this.rejectCallbacks.push(() => {
                        handleThenResult(onRejected(this.reason), resolve, reject);
                    });
                }
            }
        });
    }
}

到此then的链式调用已经处理完成了,下一节将带上promise的四个静态方法(all, race, reject, resolve)的处理。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容