squid-js/src/utils/SubscribablePromise.ts

57 lines
1.7 KiB
TypeScript
Raw Normal View History

2019-06-20 00:20:09 +02:00
import { SubscribableObserver } from './SubscribableObserver'
2019-04-24 02:37:37 +02:00
export class SubscribablePromise<T extends any, P extends any> {
private observer = new SubscribableObserver<T, P>()
2019-08-19 13:21:19 +02:00
2019-04-24 02:37:37 +02:00
private promise = Object.assign(
new Promise<P>((resolve, reject) => {
setTimeout(() => {
2019-06-20 00:20:09 +02:00
this.observer.subscribe(undefined, resolve, reject)
2019-04-24 13:25:37 +02:00
}, 0)
2019-04-24 02:37:37 +02:00
}),
2019-06-20 00:20:09 +02:00
this
2019-04-24 02:37:37 +02:00
)
2019-09-09 12:18:54 +02:00
constructor(executor: (observer: SubscribableObserver<T, P>) => void | Promise<P>) {
2019-04-25 14:15:32 +02:00
// Defear
setTimeout(() => this.init(executor), 1)
2019-04-24 02:37:37 +02:00
}
2019-04-24 13:25:37 +02:00
public subscribe(onNext: (next: T) => void) {
2019-04-24 02:37:37 +02:00
return this.observer.subscribe(onNext)
}
2019-04-24 13:25:37 +02:00
public next(onNext: (next: T) => void) {
2019-04-24 02:37:37 +02:00
this.observer.subscribe(onNext)
return this
}
2019-09-09 12:18:54 +02:00
public then(onfulfilled?: (value: P) => any, onrejected?: (error: any) => any) {
2019-04-24 02:37:37 +02:00
return Object.assign(this.promise.then(onfulfilled, onrejected), this)
}
2019-04-24 13:25:37 +02:00
public catch(onrejected?: (error: any) => any) {
2019-04-24 02:37:37 +02:00
return Object.assign(this.promise.catch(onrejected), this)
}
2019-04-24 13:25:37 +02:00
public finally(onfinally?: () => any) {
2019-04-24 02:37:37 +02:00
return Object.assign(this.promise.finally(onfinally), this)
}
2019-04-25 14:15:32 +02:00
2019-09-09 12:18:54 +02:00
private init(executor: (observer: SubscribableObserver<T, P>) => void | Promise<P>) {
2019-04-25 14:15:32 +02:00
const execution = executor(this.observer)
Promise.resolve(execution as any)
.then((result) => {
2019-06-20 00:20:09 +02:00
if (typeof (execution as any).then === 'function') {
2019-04-25 14:15:32 +02:00
this.observer.complete(result)
}
})
.catch((result) => {
2019-06-20 00:20:09 +02:00
if (typeof (execution as any).then === 'function') {
2019-04-25 14:15:32 +02:00
this.observer.error(result)
}
})
}
2019-04-24 02:37:37 +02:00
}