UNPKG

@freemework/common

Version:

Common library of the Freemework Project.

48 lines 1.85 kB
import { FInitableBase } from "./f_initable.js"; import { FExceptionArgument } from "../exception/index.js"; /** * @deprecated Use TypeScript 5.2 introduces a new keyword - 'using'. See https://github.com/tc39/proposal-explicit-resource-management */ export function FUsing(executionContext, resourceFactory, worker) { if (!resourceFactory || typeof resourceFactory !== "function") { throw new Error("Wrong argument: resourceFactory"); } if (!worker) { throw new Error("Wrong argument: worker"); } async function workerExecutor(workerExecutorCancellationToken, disposableResource) { if (disposableResource instanceof FInitableBase || "init" in disposableResource) { await disposableResource.init(executionContext); } try { let workerResult; if (worker.length === 1) { workerResult = worker(disposableResource); } else if (worker.length === 2) { workerResult = worker(workerExecutorCancellationToken, disposableResource); } else { throw new FExceptionArgument("Wrong worker function. Expect a function with 1 or 2 arguments.", "worker"); } if (workerResult instanceof Promise) { return await workerResult; } else { return workerResult; } } finally { await disposableResource.dispose(); } } const resource = resourceFactory(executionContext); if (resource instanceof Promise) { return resource .then(disposableInstance => workerExecutor(executionContext, disposableInstance)); } else { return workerExecutor(executionContext, resource); } } //# sourceMappingURL=f_using.js.map