UNPKG

softkave-js-utils

Version:

JavaScript & Typescript utility functions, types, and classes

48 lines 1.37 kB
import { isPromise } from './isPromiseLike.js'; function generateId() { return `${Date.now()}-${Math.random()}`; } export class PromiseStore { constructor(logger = console) { this.logger = logger; this.promiseRecord = {}; this.isClosed = false; } /** Returns a promise resolved when all the promises at the time of calling * are resolved. This does not include promises stored after this call. */ async flush() { await Promise.allSettled(Object.values(this.promiseRecord)); } /** Prevents addition of new promises. */ close() { this.isClosed = true; return this; } isStoreClosed() { return this.isClosed; } callAndForget(fn) { this.assertNotClosed(); const id = generateId(); try { const p = fn(); if (isPromise(p)) { this.promiseRecord[id] = p; p.catch(error => { this.logger.error(error); }).finally(() => { delete this.promiseRecord[id]; }); } } catch (error) { this.logger.error(error); } } assertNotClosed() { if (this.isClosed) { throw new Error('PromiseStore is closed'); } } } //# sourceMappingURL=PromiseStore.js.map