博客
关于我
自定义实现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/

你可能感兴趣的文章
Python3连接MySQL
查看>>
Python关于isinstance函数的解析 | 附Demo(全)
查看>>
Python3:setup.py:完成所有任务的PIP安装(Build_ext+Install)
查看>>
python4.0 gil_Python 并发编程系列--1、浅谈GIL历史及对多线程的影响
查看>>
python60行绘图程序_天底下最简单的QT画图板,就一个类,60行代码
查看>>
Python: AES加密与解密
查看>>
Python: Range() 最大尺寸;动态的还是静态的?
查看>>
Python: Windows下用 multiprocessing 的深坑
查看>>
python:Could not find platform independent libraries <prefix>解决方法
查看>>
Python:datetime tzinfo 时区名称文档
查看>>
Python:deepcopy(list) vs new_list = old_list[:]
查看>>
Python:Google API - 从消息中获取 mimeTypes
查看>>
Python:Google API - 从消息中获取 mimeTypes
查看>>
Python:subprocess.call,stdout to file,stderr to file,在屏幕上实时显示stderr
查看>>
Python:TypeError:无法连接“str“和“int“对象
查看>>
Python:XPath 在 ElementTree 中不可用
查看>>
Python:从 FTP 服务器下载文件
查看>>
python:从列表中创建元组列表
查看>>
Python:从嵌套列表中删除重复项
查看>>
Python:从间隔映射到值
查看>>