Add cancellable promise to Microsoft auth flows (#211495)

Fixes #211406
This commit is contained in:
Tyler James Leonhardt
2024-04-26 16:06:58 -07:00
committed by GitHub
parent 233775583c
commit 1357fca0f7
4 changed files with 74 additions and 38 deletions

View File

@@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Disposable } from 'vscode';
import { CancellationError, CancellationToken, Disposable } from 'vscode';
export class SequencerByKey<TKey> {
@@ -47,3 +47,36 @@ export class IntervalTimer extends Disposable {
}, interval);
}
}
/**
* Returns a promise that rejects with an {@CancellationError} as soon as the passed token is cancelled.
* @see {@link raceCancellation}
*/
export function raceCancellationError<T>(promise: Promise<T>, token: CancellationToken): Promise<T> {
return new Promise((resolve, reject) => {
const ref = token.onCancellationRequested(() => {
ref.dispose();
reject(new CancellationError());
});
promise.then(resolve, reject).finally(() => ref.dispose());
});
}
export class TimeoutError extends Error {
constructor() {
super('Timed out');
}
}
export function raceTimeoutError<T>(promise: Promise<T>, timeout: number): Promise<T> {
return new Promise((resolve, reject) => {
const ref = setTimeout(() => {
reject(new CancellationError());
}, timeout);
promise.then(resolve, reject).finally(() => clearTimeout(ref));
});
}
export function raceCancellationAndTimeoutError<T>(promise: Promise<T>, token: CancellationToken, timeout: number): Promise<T> {
return raceCancellationError(raceTimeoutError(promise, timeout), token);
}