Skip to content

Commit 9c768eb

Browse files
committed
Adds timed promise util functions
1 parent fa46041 commit 9c768eb

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/system/promise.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { CancellationToken, Disposable } from 'vscode';
2+
import { pauseOnCancelOrTimeout } from './cancellation';
23

34
export type PromiseOrValue<T> = Promise<T> | T;
45

@@ -255,6 +256,28 @@ export function isPromise<T>(obj: PromiseLike<T> | T): obj is Promise<T> {
255256
// return new Map(await Promise.all(promises));
256257
// }
257258

259+
export type TimedResult<T> = { readonly value: T; readonly duration: number };
260+
export async function timed<T>(promise: Promise<T>): Promise<TimedResult<T>> {
261+
const start = Date.now();
262+
const value = await promise;
263+
return { value: value, duration: Date.now() - start };
264+
}
265+
266+
export async function timedWithSlowThreshold<T>(
267+
promise: Promise<T>,
268+
slowThreshold: { timeout: number; onSlow: (duration: number) => void },
269+
): Promise<TimedResult<T>> {
270+
const start = Date.now();
271+
272+
const result = await pauseOnCancelOrTimeout(promise, undefined, slowThreshold.timeout);
273+
274+
const value = result.paused
275+
? await result.value.finally(() => slowThreshold.onSlow(Date.now() - start))
276+
: result.value;
277+
278+
return { value: value, duration: Date.now() - start };
279+
}
280+
258281
export function wait(ms: number): Promise<void> {
259282
return new Promise<void>(resolve => setTimeout(resolve, ms));
260283
}

0 commit comments

Comments
 (0)