JavaScript设计模式(三十三):入场仪式-等待者模式

简介: 入场仪式-等待者模式

等待者模式(waiter)

通过对多个异步进程监听,来触发未来发生的动作。(类似于 Promise Promise.all(...)

什么是等待者模式

等待者模式或者说等待者对象用来解决那些不确定先后完成的异步逻辑的

比如:运动会的入场仪式,你不确定请哪只队伍先入场,但有一点你很确定,就是会议开始必须等到所有的队伍入场完毕。而这里的会议开始就相当于等待这模式的逻辑执行

Promise.all(...)

function fnA() {
   
    let code = [0, 1][Math.floor(Math.random() * 2)];
    return new Promise((resolve, reject) => {
   
        setTimeout(function () {
   
            if (code) resolve({
    code, msg: 'success!', name: 'fnA' })
            else reject({
    code, msg: 'fail!', name: 'fnA' })
        }, 1500);
    });
}

function fnB() {
   
    let code = 1;
    return new Promise((resolve, reject) => {
   
        setTimeout(function () {
   
            if (code) resolve({
    code, msg: 'success!', name: 'fnB' })
            else reject({
    code, msg: 'fail!', name: 'fnB' })
        }, 1000);
    });
}

Promise.all([fnA(), fnB()])
    .then(res => {
   
        /**
         * [{ code: 1, msg: 'success!', name: 'fnA' }, 
         *  { code: 1, msg: 'success!', name: 'fnB' }]
         */
        console.log(res);
    })
    .catch(err => {
   
        // { code: 0, msg: 'fail!', name: 'fnA' }
        console.log(err);
    });

函数形参嵌套函数形参

/**
 * 函数形参fn 嵌套 函数形参resolve、reject
 * @param {Function} fn demo的函数行参
 *      @param {Function} resolve fn的函数形参1
 *      @param {Function} reject  fn的函数形参2
 */
function demo(fn = (resolve, reject) => {
    resolve(null); reject(null); }) {
   
    fn(resolve, reject);
    function resolve(...args) {
    console.log('resolve', args); }
    function reject(...args) {
    console.log('reject', args); }
}

demo(); // resolve->[null] reject->[null]

demo((resolve, reject) => {
   
    resolve(1, 2, 3);
    reject(4, 5, 6);
}); // resolve->[1, 2, 3] reject->[4, 5, 6]

以上代码的变式1

等待者模式完成 40%

/**
 * 函数形参fn 嵌套 函数形参resolve、reject
 * @param {Function} fn Demo的函数行参
 *      @param {Function} resolve fn的函数形参1
 *      @param {Function} reject fn的函数形参2
 */
function Demo(fn = (resolve, reject) => {
    resolve(null); reject(null); }) {
   
    let value = [];
    fn(resolve, reject);
    function resolve(...args) {
   
        value = [...value, ...args];
    }
    function reject(...args) {
   
        value = [...value, ...args];
    }
    this.then = (callback) => {
   
        callback(value);
    }
}

new Demo((resolve, reject) => {
   
    resolve(1, 2, 3);
    reject(4, 5, 6);
}).then(res => console.log(res)); // (6) [1, 2, 3, 4, 5, 6]

new Demo().then(res => console.log(res)); // [null, null]

以上代码的变式2

等待者模式完成 80%

/**
 * 函数形参fn 嵌套 函数形参resolve、reject
 * @param {Function} fn Demo的函数行参
 *      @param {Function} resolve fn的函数形参1
 *      @param {Function} reject fn的函数形参2
 */
function Demo(fn) {
   

    let state = null; // null->赋值操作  true->resolve、onFulfilled  false->reject、onRejected
    let value = [];
    let deferred = {
   };

    fn(resolve, reject);

    function resolve(...args) {
   
        state = true;
        value = args;
        deferred.onFulfilled && deferred.onFulfilled(value);
    }

    function reject(...args) {
   
        state = false;
        value = args;
        deferred.onRejected && deferred.onRejected(value);
    }

    this.then = (onFulfilled, onRejected) => {
   
        if (state === null) {
   
            deferred = {
    onFulfilled, onRejected }
        } else {
   
            (state ? onFulfilled : onRejected)(value);
        }
        return this;
    }
}

new Demo((resolve, reject) => {
   
    setTimeout(function () {
   
        resolve(1, 2, 3);
        reject(4, 5, 6);
    }, 2000);
}).then(res => {
   
    console.log('res', res); // res->[1, 2, 3]
}, err => {
   
    console.log('err', err); // err->[4, 5, 6]
});

自定义实现等待者模式(仿Promise.all)

等待者模式完成 100%

/**
 * 等待者模式
 * @param {Function} fn (resolve, reject) => { resolve('ok'); reject('fail'); }
 * @returns 实例化
 */
function Waiter(fn) {
   

    // 兼容不使用new关键字
    if (!(this instanceof Waiter)) return new Waiter(fn);

    let state = null;   // true 成功回调; false 失败回调; null 中立
    let value = null;   // 暂存`成功或失败回调的结果`,用于`后续调用.then`的`使用`
    let deferred = {
   };  // 存储.then(...)传入的参数 ---> { onFulfilled, onRejected }

    fn(resolve, reject);

    /**
     * 接收成功失败回调
     * @param {Function} onFulfilled 成功回调
     * @param {Function} onRejected  失败回调
     * @returns 当前实例
     */
    this.then = function (onFulfilled, onRejected) {
   
        if (state === null) {
   
            deferred = {
    onFulfilled, onRejected };
        } else {
   
            (state ? onFulfilled : onRejected)(value);
        }
        return this;
    };

    /**
     * 成功回调
     * @param {any} val 结果
     */
    function resolve(val) {
   
        if (state !== null) return;
        state = true;
        value = val;
        deferred.onFulfilled && deferred.onFulfilled(value);
        deferred = null;
    }

    /**
     * 失败回调
     * @param {any} val 结果
     */
    function reject(val) {
   
        if (state !== null) return;
        state = false;
        value = val;
        deferred.onRejected && deferred.onRejected(value);
        deferred = null;
    }

}

/**
 * 等待所传函数全部完成
 * @param  {...any} args 任意参数
 * @returns Waiter实例
 */
Waiter.all = (...args) => {
   
    // 如果参数只有一个并且是数组,那么使用这个数组;如果参数为多个,那么使用参数组合成的数组;
    let arr = (args.length === 1 && Array.isArray(args[0])) ? args[0] : args;
    return new Waiter(function (resolve, reject) {
   
        // 如果未传参,则返回空数组
        if (arr.length === 0) return resolve([]);
        // 还需处理的对象数量计数器
        let remaining = arr.length;
        // 处理传参保存结果函数
        function result(w, i) {
   
            if (w instanceof Waiter) {
   
                w.then(function (res) {
    result(res, i); }, reject);
                return;
            }
            // 完成一个替换一个
            arr[i] = w;
            if (--remaining === 0) {
   
                resolve(arr);
            }
        }
        arr.forEach((w, i) => result(w, i));
    });
};
const w1 = new Waiter((resolve, reject) => {
   
    setTimeout(() => {
   
        Math.random() > 0.5 ? resolve(1) : reject(0);
    }, 2000);
}).then(res => console.log('res', res), err => console.log('err', err));
// 返回对象,成功或失败回调
function fnA() {
   
    return new Waiter((resolve, reject) => {
   
        setTimeout(() => {
   
            Math.random() > 0.5 ? resolve({
    name: 'A', msg: 'success' }) : reject({
    name: 'A', msg: 'fail' });
        }, 100);
    });
}
// 返回对象,成功回调
function fnB() {
   
    return new Waiter((resolve, reject) => {
   
        setTimeout(() => {
   
            resolve({
    name: 'B', msg: 'success' });
        }, 3000);
    });
}
// 返回数字,成功回调
function fnC() {
   
    return new Waiter((resolve, reject) => {
   
        setTimeout(() => {
   
            resolve(123);
        }, 1000);
    });
}

const w2 = Waiter.all([fnB(), fnA(), fnC(), 'abc', 456])
    .then(res => console.log(JSON.stringify(res)), err => console.log(err));

等待者模式(ES6写法)

class Waiter {
   
    #state = null;  // true 成功回调; false 失败回调; null 中立
    #value = null;  // 暂存`成功或失败回调的结果`,用于`后续调用.then`的`使用`
    #deferred = {
   }; // 存储.then(...)传入的参数 ---> { onFulfilled, onRejected }
    constructor(fn) {
   
        // 兼容不使用new关键字
        if (!(this instanceof Waiter)) return new Waiter(fn);
        fn(this.#resolve, this.#reject);
    }
    /**
     * 接收成功失败回调
     * @param {Function} onFulfilled 成功回调
     * @param {Function} onRejected  失败回调
     * @returns 当前实例
     */
    then = function (onFulfilled, onRejected) {
   
        if (this.#state === null) {
   
            this.#deferred = {
    onFulfilled, onRejected };
        } else {
   
            (this.#state ? onFulfilled : onRejected)(this.#value);
        }
        return this;
    };
    /**
     * 成功回调
     * @param {any} val 结果
     */
    #resolve = (val) => {
   
        if (this.#state !== null) return;
        this.#state = true;
        this.#value = val;
        this.#deferred.onFulfilled && this.#deferred.onFulfilled(this.#value);
        this.#deferred = null;
    };
    /**
     * 失败回调
     * @param {any} val 结果
     */
    #reject = (val) => {
   
        if (this.#state !== null) return;
        this.#state = false;
        this.#value = val;
        this.#deferred.onRejected && this.#deferred.onRejected(this.#value);
        this.#deferred = null;
    };
    /**
     * 等待所传函数全部完成
     * @param  {...any} args 任意参数
     * @returns Waiter实例
     */
    static all = (...args) => {
   
        // 如果参数只有一个并且是数组,那么使用这个数组;如果参数为多个,那么使用参数组合成的数组;
        let arr = (args.length === 1 && Array.isArray(args[0])) ? args[0] : args;
        return new Waiter(function (resolve, reject) {
   
            // 如果未传参,则返回空数组
            if (arr.length === 0) return resolve([]);
            // 还需处理的对象数量计数器
            let remaining = arr.length;
            // 处理传参保存结果函数
            function result(w, i) {
   
                if (w instanceof Waiter) {
   
                    w.then(function (res) {
    result(res, i); }, reject);
                    return;
                }
                // 完成一个替换一个
                arr[i] = w;
                if (--remaining === 0) {
   
                    resolve(arr);
                }
            }
            arr.forEach((w, i) => result(w, i));
        });
    };
}
const w1 = new Waiter((resolve, reject) => {
   
    setTimeout(() => {
   
        Math.random() > 0.5 ? resolve({
    msg: 'success' }) : reject({
    msg: 'fail' });
    }, 5000);
}).then(res => console.log('res', res), err => console.log('err', err));
// 返回对象,成功或失败回调
function fnA() {
   
    return new Waiter((resolve, reject) => {
   
        setTimeout(() => {
   
            Math.random() > 0.5 ? resolve({
    name: 'A', msg: 'success' }) : reject({
    name: 'A', msg: 'fail' });
        }, 100);
    });
}
// 返回对象,成功回调
function fnB() {
   
    return new Waiter((resolve, reject) => {
   
        setTimeout(() => {
   
            resolve({
    name: 'B', msg: 'success' });
        }, 3000);
    });
}
// 返回数字,成功回调
function fnC() {
   
    return new Waiter((resolve, reject) => {
   
        setTimeout(() => {
   
            resolve(123);
        }, 1000);
    });
}

const w2 = Waiter.all([fnB(), fnA(), fnC(), 'abc'])
    .then(res => console.log(JSON.stringify(res)), err => console.log(err));
目录
相关文章
|
7月前
|
设计模式 Java 数据库连接
【设计模式】【创建型模式】工厂方法模式(Factory Methods)
一、入门 什么是工厂方法模式? 工厂方法模式(Factory Method Pattern)是一种创建型设计模式,它定义了一个用于创建对象的接口,但由子类决定实例化哪个类。工厂方法模式使类的实例化延迟
212 16
|
7月前
|
设计模式 负载均衡 监控
并发设计模式实战系列(2):领导者/追随者模式
🌟 ​大家好,我是摘星!​ 🌟今天为大家带来的是并发设计模式实战系列,第二章领导者/追随者(Leader/Followers)模式,废话不多说直接开始~
220 0
|
7月前
|
设计模式 监控 Java
并发设计模式实战系列(1):半同步/半异步模式
🌟 ​大家好,我是摘星!​ 🌟今天为大家带来的是并发设计模式实战系列,第一章半同步/半异步(Half-Sync/Half-Async)模式,废话不多说直接开始~
205 0
|
7月前
|
设计模式 安全 Java
并发设计模式实战系列(12):不变模式(Immutable Object)
🌟 大家好,我是摘星!🌟今天为大家带来的是并发设计模式实战系列,第十二章,废话不多说直接开始~
178 0
|
7月前
|
设计模式 算法 Java
设计模式觉醒系列(04)策略模式|简单工厂模式的升级版
本文介绍了简单工厂模式与策略模式的概念及其融合实践。简单工厂模式用于对象创建,通过隐藏实现细节简化代码;策略模式关注行为封装与切换,支持动态替换算法,增强灵活性。两者结合形成“策略工厂”,既简化对象创建又保持低耦合。文章通过支付案例演示了模式的应用,并强调实际开发中应根据需求选择合适的设计模式,避免生搬硬套。最后推荐了JVM调优、并发编程等技术专题,助力开发者提升技能。
|
12月前
|
设计模式 前端开发 搜索推荐
前端必须掌握的设计模式——模板模式
模板模式(Template Pattern)是一种行为型设计模式,父类定义固定流程和步骤顺序,子类通过继承并重写特定方法实现具体步骤。适用于具有固定结构或流程的场景,如组装汽车、包装礼物等。举例来说,公司年会节目征集时,蜘蛛侠定义了歌曲的四个步骤:前奏、主歌、副歌、结尾。金刚狼和绿巨人根据此模板设计各自的表演内容。通过抽象类定义通用逻辑,子类实现个性化行为,从而减少重复代码。模板模式还支持钩子方法,允许跳过某些步骤,增加灵活性。
673 11
|
7月前
|
设计模式 Prometheus 监控
并发设计模式实战系列(20):扇出/扇入模式(Fan-Out/Fan-In)(完结篇)
🌟 大家好,我是摘星!🌟今天为大家带来的是并发设计模式实战系列,第二十章,废话不多说直接开始~
243 0
|
10月前
|
JavaScript 前端开发 Docker
如何通过pm2以cluster模式多进程部署next.js(包括docker下的部署)
通过这些步骤,可以确保您的Next.js应用在多核服务器上高效运行,并且在Docker环境中实现高效的容器化管理。
1012 44
|
11月前
|
设计模式
「全网最细 + 实战源码案例」设计模式——模式扩展(配置工厂)
该设计通过配置文件和反射机制动态选择具体工厂,减少硬编码依赖,提升系统灵活性和扩展性。配置文件解耦、反射创建对象,新增产品族无需修改客户端代码。示例中,`CoffeeFactory`类加载配置文件并使用反射生成咖啡对象,客户端调用时只需指定名称即可获取对应产品实例。
225 40
|
9月前
|
设计模式 Java 关系型数据库
设计模式:工厂方法模式(Factory Method)
工厂方法模式是一种创建型设计模式,通过将对象的创建延迟到子类实现解耦。其核心是抽象工厂声明工厂方法返回抽象产品,具体工厂重写该方法返回具体产品实例。适用于动态扩展产品类型、复杂创建逻辑和框架设计等场景,如日志记录器、数据库连接池等。优点包括符合开闭原则、解耦客户端与具体产品;缺点是可能增加类数量和复杂度。典型应用如Java集合框架、Spring BeanFactory等。

热门文章

最新文章