摘自https://github.com/zombieJ/notify-promise

class NotifyPromise {
promise: Promise;
done: boolean = false;
notifyList: Array<(value: any,index: number) => void> = [];
notifyIndex: number = 0;

constructor(func: ((resolve: Function,reject: Function,notify: Function) => NotifyPromise) | Promise<any>) {
    if (typeof func === 'function') {
        this.promise = new Promise((resolve,reject) => {
            const doOperation = (operate) => (
                (value) => {
                    this.done = true;

                    setImmediate(() => {
                        operate(value);
                    });
                }
            );

            func(doOperation(resolve),doOperation(reject),this.doNotify);
        });
    } else {
        this.promise = func;
    }
}

then = (onResolve: (value?: any) => NotifyPromise,onReject: (value?: any) => NotifyPromise) => {
    const nextPromise: Promise<any> = this.promise.then(onResolve,onReject);
    const instance = new NotifyPromise(nextPromise);
    instance.__notifyList = this.__notifyList;
    return instance;
};

catch = (onReject: (value?: any) => NotifyPromise) => {
    const nextPromise: Promise<any> = this.promise.catch(onReject);
    const instance = new NotifyPromise(nextPromise);
    instance.__notifyList = this.__notifyList;
    return instance;
};

doNotify = (message: any) => {
    if (this.done) return;

    setImmediate(() => {
        this.__notifyList.forEach(func => {
            func(message,this.__notifyIndex);
        });

        this.__notifyIndex += 1;
    });
};

notify = (func: (value: any,index: number) => void) => {
    const instance = new NotifyPromise(this.promise);
    instance.__notifyList = this.__notifyList;
    instance.__notifyList.push(func);
    return instance;
};

}

export default NotifyPromise;

相关文章

developer-roadmap —— 提供最全的开发者技术路线指南。前端...
一个极简的文件分享工具,无需注册且没有广告即可生成共享下...
收集 Github、Gitee优秀的开源项目,并进行归类整理。项目地...
大家好,我是 Java陈序员,我们有时会搭建一个属于自己的网站...
一个提供交互式的Web UI用于生成兼容MyBatisPlus框架的相关功...
大家好,我是 Java 陈序员。权限认证是我们日常开发绕不过的...