@@ -66,7 +66,7 @@ type AsyncOperation<T> = () => Promise<T>;
6666 * const data2 = await dataLoader.do(); // If first promise is finished, a new fetch is executed
6767 */
6868export class AsyncMutex < T = unknown > {
69- private currentOperation : Promise < any > | null = null ;
69+ private currentOperation : Promise < T > | null = null ;
7070 private defaultOperation ?: AsyncOperation < T > ;
7171
7272 /**
@@ -97,12 +97,6 @@ export class AsyncMutex<T = unknown> {
9797 this . defaultOperation = operation ;
9898 }
9999
100- /**
101- * Executes the default operation if one was provided in the constructor.
102- * @returns Promise that resolves with the result of the default operation
103- * @throws Error if no default operation was set in the constructor
104- */
105- do ( ) : Promise < T > ;
106100 /**
107101 * Executes the provided operation, ensuring only one runs at a time.
108102 *
@@ -126,32 +120,29 @@ export class AsyncMutex<T = unknown> {
126120 * await promise1;
127121 * const newPromise = mutex.do(() => fetch('/api/new')); // This will execute
128122 */
129- do < U > ( operation : AsyncOperation < U > ) : Promise < U > ;
130- do < U = T > ( operation ?: AsyncOperation < U > ) : Promise < U | T > {
131- if ( ! operation && ! this . defaultOperation ) {
123+ do ( operation ?: AsyncOperation < T > ) : Promise < T > {
124+ if ( this . currentOperation ) {
125+ return this . currentOperation ;
126+ }
127+ const op = operation ?? this . defaultOperation ;
128+ if ( ! op ) {
132129 return Promise . reject (
133130 new Error ( "No operation provided and no default operation set" )
134131 ) ;
135132 }
136-
137- if ( this . currentOperation ) {
138- return this . currentOperation ;
139- }
140-
141- const op = ( operation || this . defaultOperation ) as AsyncOperation < U | T > ;
142133 const safeOp = ( ) => {
143134 try {
144135 return op ( ) ;
145136 } catch ( error ) {
146137 return Promise . reject ( error ) ;
147138 }
148139 } ;
140+
149141 const promise = safeOp ( ) . finally ( ( ) => {
150142 if ( this . currentOperation === promise ) {
151143 this . currentOperation = null ;
152144 }
153145 } ) ;
154-
155146 this . currentOperation = promise ;
156147 return promise ;
157148 }
0 commit comments