Skip to content

Commit

Permalink
feat: add withReady()
Browse files Browse the repository at this point in the history
  • Loading branch information
rocwind committed Mar 10, 2021
1 parent 8ac4e75 commit 425c48d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { wait, ReadyStatusEnum } from '../index';
import { wait, ReadyStatusEnum, withReady } from '../index';

it('resolves with no value set', () => {
const { setReady, afterReady } = wait();
Expand Down Expand Up @@ -77,3 +77,9 @@ it('can set target name', () => {
setMyTaskReady();
return expect(afterMyTaskReady()).resolves.toBeUndefined();
});

it('can wait ready for function withReady', () => {
const myFunc = (a: number, b: number) => a + b;
const myFuncWithReady = withReady(myFunc, Promise.resolve());
return expect(myFuncWithReady(1, 2)).resolves.toBe(3);
});
18 changes: 18 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,21 @@ export const wait = <T, Name extends string = ''>(name?: Name): WaitReturn<T, Na
},
} as WaitReturn<T, Name>;
};

type ParametersTypes<T> = T extends (...args: infer P) => unknown ? P : [];
type Promisify<T> = T extends Promise<unknown> ? T : Promise<T>;

/**
* wrap function to have it run after ready promise resolves
* @param func
* @param ready promise to wait for
* @returns wrapped function returns, promisified
*/
export function withReady<T extends (...args: unknown[]) => unknown>(
func: T,
ready: Promise<unknown>,
): (...args: ParametersTypes<T>) => Promisify<ReturnType<T>> {
return ((...args: ParametersTypes<T>) => {
return ready.then(() => func(...args));
}) as (...args: ParametersTypes<T>) => Promisify<ReturnType<T>>;
}

0 comments on commit 425c48d

Please sign in to comment.