摘自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;

相关文章

咱们在vscode中使用copilot的过程中,有可能会涉及到个人账号...
这篇文章给大家介绍怎么在GitHub上快速找到实用资源,内容非...
这篇文章主要介绍“github缓存穿透的解决方法是什么”,在日...
本篇内容介绍了“github线性回归怎么实现”的有关知识,在实...
怎样使用GitHub,很多新手对此不是很清楚,为了帮助大家解决...
今天小编给大家分享一下GitHub的高级搜索方法有哪些的相关知...