加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 16:37:55 所属栏目:百科 来源:网络整理
导读: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) | Pr
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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读