diff --git a/src/common/lib/util/multicaster.ts b/src/common/lib/util/multicaster.ts index 81f1fb6344..eb7ba19b28 100644 --- a/src/common/lib/util/multicaster.ts +++ b/src/common/lib/util/multicaster.ts @@ -5,6 +5,18 @@ import Logger from './logger'; export interface MulticasterInstance extends Function { (err?: ErrorInfo | null, result?: T): void; push: (fn: StandardCallback) => void; + /** + * Creates a promise that will be resolved or rejected when this instance is called. + */ + createPromise: () => Promise; + /** + * Syntatic sugar for when working in a context that uses promises; equivalent to calling as a function with arguments (null, result). + */ + resolveAll(result: T): void; + /** + * Syntatic sugar for when working in a context that uses promises; equivalent to calling as a function with arguments (err). + */ + rejectAll(err: ErrorInfo): void; } class Multicaster { @@ -35,10 +47,29 @@ class Multicaster { this.members.push(...args); } + createPromise(): Promise { + return new Promise((resolve, reject) => { + this.push((err, result) => { + err ? reject(err) : resolve(result!); + }); + }); + } + + resolveAll(result: T) { + this.call(null, result); + } + + rejectAll(err: ErrorInfo) { + this.call(err); + } + static create(members?: Array | undefined>): MulticasterInstance { const instance = new Multicaster(members); return Object.assign((err?: ErrorInfo | null, result?: T) => instance.call(err, result), { push: (fn: StandardCallback) => instance.push(fn), + createPromise: () => instance.createPromise(), + resolveAll: (result: T) => instance.resolveAll(result), + rejectAll: (err: ErrorInfo) => instance.rejectAll(err), }); } }