Skip to content

2776. Convert Callback Based Function to Promise Based Function

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type CallbackFn = (
  next: (data: number, error: string) => void,
  ...args: number[]
) => void;
type Promisified = (...args: number[]) => Promise<number>;

function promisify(fn: CallbackFn): Promisified {
  return async function (...args: number[]): Promise<number> {
    return new Promise((resolve, reject) =>
      fn((data, err) => (err ? reject(err) : resolve(data)), ...args)
    );
  };
}