Skip to content

Commit

Permalink
Add a method for bridging Multicaster with promises
Browse files Browse the repository at this point in the history
Preparation for using promises internally in the codebase.

Part of #1535; will remove the functional interface to Multicaster
if/when it’s no longer needed.
  • Loading branch information
lawrence-forooghian committed Jan 11, 2024
1 parent dfde71e commit 389a8f5
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/common/lib/util/multicaster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ import Logger from './logger';
export interface MulticasterInstance<T> extends Function {
(err?: ErrorInfo | null, result?: T): void;
push: (fn: StandardCallback<T>) => void;
/**
* Creates a promise that will be resolved or rejected when this instance is called.
*/
createPromise: () => Promise<T>;
/**
* 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<T> {
Expand Down Expand Up @@ -35,10 +47,29 @@ class Multicaster<T> {
this.members.push(...args);
}

createPromise(): Promise<T> {
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<T>(members?: Array<StandardCallback<T> | undefined>): MulticasterInstance<T> {
const instance = new Multicaster(members);
return Object.assign((err?: ErrorInfo | null, result?: T) => instance.call(err, result), {
push: (fn: StandardCallback<T>) => instance.push(fn),
createPromise: () => instance.createPromise(),
resolveAll: (result: T) => instance.resolveAll(result),
rejectAll: (err: ErrorInfo) => instance.rejectAll(err),
});
}
}
Expand Down

0 comments on commit 389a8f5

Please sign in to comment.