Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/util/common/racePromise.ts
13397 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import { raceCancellation, raceTimeout } from '../vs/base/common/async';
7
import { CancellationToken, CancellationTokenSource } from '../vs/base/common/cancellation';
8
import { CancellationError } from '../vs/base/common/errors';
9
10
// sentinel value to indicate cancellation
11
const CANCELLED = Symbol('cancelled');
12
13
/**
14
* Races a promise against a cancellation token and a timeout.
15
* @param promiseGenerator A function that generates the promise to race against cancellation and timeout.
16
* @param parentToken The cancellation token to use.
17
* @param timeoutInMs The timeout in milliseconds.
18
* @param timeoutMessage The message to use for the timeout error.
19
* @returns The result of the promise if it completes before the timeout, or throws an error if it times out or is cancelled.
20
*/
21
export async function raceTimeoutAndCancellationError<T>(
22
promiseGenerator: (cancellationToken: CancellationToken) => Promise<T>,
23
parentToken: CancellationToken,
24
timeoutInMs: number,
25
timeoutMessage: string): Promise<T> {
26
const cancellationSource = new CancellationTokenSource(parentToken);
27
try {
28
const result = await raceTimeout(raceCancellation(promiseGenerator(cancellationSource.token), cancellationSource.token, CANCELLED as T), timeoutInMs);
29
30
if (result === CANCELLED) { // cancelled sentinel from raceCancellation
31
throw new CancellationError();
32
}
33
34
if (result === undefined) { // timeout sentinel from raceTimeout
35
// signal ongoing work to cancel in the promise
36
cancellationSource.cancel();
37
throw new Error(timeoutMessage);
38
}
39
40
return result;
41
}
42
finally {
43
cancellationSource.dispose();
44
}
45
}
46