UNPKG

lib-comfoair

Version:

Library to communicate with Zehnder ComfoAirQ ventilation unit through the ComfoControl gateway

70 lines (69 loc) 2.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DeferredPromise = void 0; /** * Deferred promise implementation. */ class DeferredPromise { #innerPromise; #reject; #resolve; #isResolved = false; get [Symbol.toStringTag]() { return this.#innerPromise[Symbol.toStringTag]; } get isResolved() { return this.#isResolved; } /** * Create a new deferrable promise which supports resolving it outside of the context of the promise. * @param promise Optionally a promise to wrap. */ constructor(promise) { this.reset(); if (promise) { void promise.then(this.resolve.bind(this)); promise.catch(this.reject.bind(this)); } } /** * Bind the current promise to another promise, resolving or rejecting the current promise when the other promise is resolved or rejected. * @param other The other promise to bind to. * @returns The current promise. */ bind(other) { other.then(this.resolve.bind(this)).catch(this.reject.bind(this)); return this; } reset() { this.#innerPromise = new Promise((resolve, reject) => { this.#reject = reject; this.#resolve = resolve; this.#isResolved = false; }); } reject(err) { if (this.#isResolved) { throw new Error('Promise is already resolved or rejected, cannot reject or resolve a promise twice.'); } this.#isResolved = true; this.#reject(err); } resolve(result) { if (this.#isResolved) { throw new Error('Promise is already resolved or rejected, cannot reject or resolve a promise twice.'); } this.#isResolved = true; this.#resolve(result); } then(onfulfilled, onrejected) { return this.#innerPromise.then(onfulfilled, onrejected); } catch(onrejected) { return this.#innerPromise.catch(onrejected); } finally(onFinally) { return this.#innerPromise.finally(onFinally); } } exports.DeferredPromise = DeferredPromise;