Skip to content

Commit 628978a

Browse files
committed
Add combineParallelCalls
1 parent 16459ac commit 628978a

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/promises.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,25 @@ export function getDeferred<T = void>(): Deferred<T> {
4343
// TS thinks we're using these before they're assigned, which is why
4444
// we need the undefined types, and the any here.
4545
return { resolve, reject, promise } as any;
46+
}
47+
48+
/**
49+
* Wrap a function, so that any parallel calls which happen while the async function
50+
* is pending return the same value as the first call (so the function is only run
51+
* once, but the result is shared). This is useful for expensive async functions or
52+
* race conditions. This ignores arguments completely, and is only applicable for
53+
* functions that don't need any other input.
54+
*/
55+
export function combineParallelCalls<T>(fn: () => Promise<T>): () => Promise<T> {
56+
let pendingPromise: Promise<T> | undefined;
57+
58+
return () => {
59+
if (pendingPromise === undefined) {
60+
pendingPromise = fn().finally(() => {
61+
pendingPromise = undefined;
62+
});
63+
}
64+
65+
return pendingPromise;
66+
};
4667
}

0 commit comments

Comments
 (0)