Browse Source

Adds pending flag to Deferred

main
Eric Amodio 1 year ago
parent
commit
1f5062490a
2 changed files with 23 additions and 4 deletions
  1. +7
    -0
      src/system/event.ts
  2. +16
    -4
      src/system/promise.ts

+ 7
- 0
src/system/event.ts View File

@ -65,8 +65,10 @@ export function promisifyDeferred(
let cancel: ((reason?: any) => void) | undefined;
let disposable: Disposable;
let pending = true;
const promise = new Promise<U>((resolve, reject) => {
cancel = () => {
pending = false;
cancel = undefined;
reject();
};
@ -74,7 +76,9 @@ export function promisifyDeferred(
disposable = event(async (value: T) => {
try {
await executor(value, resolve, reject);
pending = false;
} catch (ex) {
pending = false;
reject(ex);
}
});
@ -90,6 +94,9 @@ export function promisifyDeferred(
);
return {
get pending() {
return pending;
},
promise: promise,
cancel: () => cancel?.(),
};

+ 16
- 4
src/system/promise.ts View File

@ -126,16 +126,28 @@ export function cancellable(
}
export interface Deferred<T> {
promise: Promise<T>;
readonly pending: boolean;
readonly promise: Promise<T>;
fulfill: (value: T) => void;
cancel(): void;
}
export function defer<T>(): Deferred<T> {
const deferred: Deferred<T> = { promise: undefined!, fulfill: undefined!, cancel: undefined! };
const deferred: Mutable<Deferred<T>> = {
pending: true,
promise: undefined!,
fulfill: undefined!,
cancel: undefined!,
};
deferred.promise = new Promise((resolve, reject) => {
deferred.fulfill = resolve;
deferred.cancel = reject;
deferred.fulfill = function (value) {
deferred.pending = false;
return resolve(value);
};
deferred.cancel = function () {
deferred.pending = false;
reject();
};
});
return deferred;
}

Loading…
Cancel
Save