Elffuss BraidHub

kikocis/continue public

main · 1.6 KiBRawPermalink
1import { Disposable, Event, EventEmitter } from "vscode";
2
3export interface PromiseAdapter<T, U> {
4 (
5 value: T,
6 resolve: (value: U | PromiseLike<U>) => void,
7 reject: (reason: any) => void,
8 ): any;
9}
10
11const passthrough = (value: any, resolve: (value?: any) => void) =>
12 resolve(value);
13
14/**
15 * Return a promise that resolves with the next emitted event, or with some future
16 * event as decided by an adapter.
17 *
18 * If specified, the adapter is a function that will be called with
19 * `(event, resolve, reject)`. It will be called once per event until it resolves or
20 * rejects.
21 *
22 * The default adapter is the passthrough function `(value, resolve) => resolve(value)`.
23 *
24 * @param event the event
25 * @param adapter controls resolution of the returned promise
26 * @returns a promise that resolves or rejects as specified by the adapter
27 */
28export function promiseFromEvent<T, U>(
29 event: Event<T>,
30 adapter: PromiseAdapter<T, U> = passthrough,
31): { promise: Promise<U>; cancel: EventEmitter<void> } {
32 let subscription: Disposable;
33 let cancel = new EventEmitter<void>();
34
35 return {
36 promise: new Promise<U>((resolve, reject) => {
37 cancel.event((_) => reject("Cancelled"));
38 subscription = event((value: T) => {
39 try {
40 Promise.resolve(adapter(value, resolve, reject)).catch(reject);
41 } catch (error) {
42 reject(error);
43 }
44 });
45 }).then(
46 (result: U) => {
47 subscription.dispose();
48 return result;
49 },
50 (error) => {
51 subscription.dispose();
52 throw error;
53 },
54 ),
55 cancel,
56 };
57}