博客
关于我
自定义实现Promise
阅读量:727 次
发布时间:2019-03-21

本文共 4233 字,大约阅读时间需要 14 分钟。

MyPromise是一个异步编程模型的核心抽象,它定义了Promise对象的创建、状态管理和操作方法。由于Promise在JavaScript中具有广泛的应用场景,本文将详细介绍自定义实现的MyPromise类及其相关方法。

MyPromise的定义

MyPromise类包含了Promise的三种状态:PENDING(初始状态)、FULFILLED(成功态)和REJECTED(失败态)。该类通过构造函数初始化 자신의状态、回调存储器以及默认值。构造函数接收一个执行器函数,该函数决定Promise的最终状态。

class MyPromise {    static PENDING = "pending";    static FULFILLED = "fulfilled";    static REJECTED = "rejected";    constructor(executor) {        this.status = MyPromise.PENDING;        this.callbacks = [];        this.value = undefined;        executor(this.resolve.bind(this), this.reject.bind(this));    }}

Promise的状态管理

当构造函数执行执行器函数时,会调用resolve或reject函数。通过 binds方法,将当前的this传入到这些函数中,以确保正确绑定上下文。

try {    executor(this.resolve.bind(this), this.reject.bind(this));} catch (error) {    this.reject(error);}

成功和失败处理

当resolve(成功处理)或reject(失败处理)方法被调用时,它们根据当前的状态进行操作。如果状态是PENDING,会更新为FULFILLED或REJECTED,并执行对应的回调。

resolve(value) {    if (this.status === MyPromise.PENDING) {        this.status = MyPromise.FULFILLED;        this.value = value;        setTimeout(() => {            this.callbacks.forEach(callback => {                callback.onResolve(value);            });        });    }}reject(reason) {    if (this.status === MyPromise.PENDING) {        this.status = MyPromise.REJECTED;        this.value = reason;        setTimeout(() => {            this.callbacks.forEach(callback => {                callback.onRejected(value);            });        });    }}

then方法的链式性质

then方法允许 promise 对结果进行进一步处理,支持链式调用。若用户未提供处理函数,则默认返回当前的value。

then(onResolve, onRejected) {    if (typeof onResolve !== "function") {        onResolve = () => this.value;    }    if (typeof onRejected !== "function") {        onRejected = () => this.value;    }    const promise = new MyPromise((resolve, reject) => {        if (this.status === MyPromise.FULFILLED) {            this.parse(promise, onResolve(this.value), resolve, reject);        } else if (this.status === MyPromise.REJECTED) {            this.parse(promise, onRejected(this.value), resolve, reject);        } else {            this.callbacks.push({                onResolve: value => this.parse(promise, onResolve(value), resolve, reject),                onRejected: value => this.parse(promise, onRejected(value), resolve, reject)            });        }    });    return promise;}

parse方法

parse方法用于异步地分割处理结果,避免多个回调同时执行。通过setTimeout确保等待之前的操作完成。

parse(promise, result, resolve, reject) {    setTimeout(() => {        if (promise === result) {            throw new TypeError("Chaining cycle detected");        }                try {            if (result instanceof MyPromise) {                result.then(resolve, reject);            } else {                resolve(result);            }        } catch (error) {            reject(error);        }    });}

Promise的静态方法

MyPromise提供了多种静态方法,如resolve和reject,可以用来将普通值或其他Promise对象转换为MyPromise实例。

static resolve(value) {    return new MyPromise((resolve, reject) => {        if (value instanceof MyPromise) {            value.then(resolve, reject);        } else {            resolve(value);        }    });}static reject(value) {    return new MyPromise((resolve, reject) => {        if (value instanceof MyPromise) {            value.then(resolve, reject);        } else {            reject(value);        }    });}

Promise的集合处理方法

MyPromise支持对多个Promise对象进行同时处理。all方法确保所有Promise执行完毕后再返回结果。

static all(promises) {    const values = [];        return new MyPromise((resolve, reject) => {        promises.forEach(promise => {            promise.then(                value => {                    values.push(value);                    if (values.length === promises.length) {                        resolve(values);                    }                },                reason => {                    reject(reason);                }            );        });    });}

Promise的竞赛处理方法

race方法返回一个Promise,为第一个完成的任务提供结果。

static race(promises) {    return new MyPromise((resolve, reject) => {        promises.forEach(promise => {            promise.then(                value => {                    resolve(value);                },                reason => {                    reject(reason);                }            );        });    });}

通过上述方法,MyPromise实现了基本的异步编程功能,可满足大多数Promise使用场景。

转载地址:http://rxsgz.baihongyu.com/

你可能感兴趣的文章
Objective-C实现adaboost算法(附完整源码)
查看>>
Objective-C实现Adler32算法(附完整源码)
查看>>
Objective-C实现AES算法(附完整源码)
查看>>
Objective-C实现AffineCipher仿射密码算法(附完整源码)
查看>>
Objective-C实现aliquot sum等分求和算法(附完整源码)
查看>>
Objective-C实现all combinations所有组合算法(附完整源码)
查看>>
Objective-C实现all permutations所有排列算法(附完整源码)
查看>>
Objective-C实现all subsequences所有子序列算法(附完整源码)
查看>>
Objective-C实现AlphaNumericalSort字母数字排序算法(附完整源码)
查看>>
Objective-C实现alternate disjoint set不相交集算法(附完整源码)
查看>>
Objective-C实现alternative list arrange备选列表排列算法(附完整源码)
查看>>
Objective-C实现An Armstrong number阿姆斯特朗数算法(附完整源码)
查看>>
Objective-C实现anagrams字谜算法(附完整源码)
查看>>
Objective-C实现ApproximationMonteCarlo蒙特卡洛方法计算pi值算法 (附完整源码)
查看>>
Objective-C实现area under curve曲线下面积算法(附完整源码)
查看>>
Objective-C实现arithmetic算术算法(附完整源码)
查看>>
Objective-C实现armstrong numbers阿姆斯壮数算法(附完整源码)
查看>>
Objective-C实现articulation-points(关键点)(割点)算法(附完整源码)
查看>>
Objective-C实现atoi函数功能(附完整源码)
查看>>
Objective-C实现average absolute deviation平均绝对偏差算法(附完整源码)
查看>>