Skip to content

Commit

Permalink
lazyThenable: revise comment & signerature
Browse files Browse the repository at this point in the history
  • Loading branch information
jokester committed Apr 6, 2024
1 parent b8dacf1 commit 9139a3c
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
3 changes: 2 additions & 1 deletion src/concurrency/lazy-thenable.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ describe(lazyThenable, () => {
await wait(0);
expect(called).toEqual(1);
expect(await converted).toEqual(1);
expect(await lazy1).toEqual(1);
expect(called).toEqual(1);
});

it('run actual action at most once', async () => {
let called = 0;
const lazy2 = lazyThenable(async () => ++called);
const lazy2 = lazyThenable(() => ++called);

expect(await lazy2).toEqual(1);
for (let i = 0; i < 10; i++) {
Expand Down
9 changes: 5 additions & 4 deletions src/concurrency/lazy-thenable.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
/**
* create a lazy, at-most-once PromiseLike from async function
* create a lazy PromiseLike to run {@name io} at most once and only after being awaited
* @param io
* @return
*/
export function lazyThenable<T>(io: () => PromiseLike<T>): PromiseLike<T> {
let r: null | Promise<T> = null;
export function lazyThenable<T>(io: () => T): PromiseLike<Awaited<T>> {
let r: null | Promise<Awaited<T>> = null;
return {
then<TResult1, TResult2 = never>(
onfulfilled?: ((value: T) => PromiseLike<TResult1> | TResult1) | undefined | null,
onfulfilled?: ((value: Awaited<T>) => PromiseLike<TResult1> | TResult1) | undefined | null,
onrejected?: ((reason: any) => PromiseLike<TResult2> | TResult2) | undefined | null,
): PromiseLike<TResult1 | TResult2> {
return (r ??= Promise.resolve(io())).then(onfulfilled, onrejected);
Expand Down

0 comments on commit 9139a3c

Please sign in to comment.