UNPKG

node-json-db

Version:

Database using JSON file as storage for Node.JS

67 lines 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.writeLockAsync = exports.readLockAsync = void 0; const ReadWriteLock = require("rwlock"); const Error_1 = require("./Error"); const lock = new ReadWriteLock(); /** * take a read lock that will be released when the function has finished running * @param func * @param timeout time in ms to wait to get the lock. Null mean infinite. */ const readLockAsync = (func, timeout = null) => { let options = {}; if (timeout != null) { options = { timeout }; } return new Promise((resolve, reject) => { lock.readLock(async (release) => { try { const result = await func(); resolve(result); } catch (e) { reject(e); } finally { release(); } }, { ...options, timeoutCallback() { reject(new Error_1.TimeoutError("Timeout", 100)); } }); }); }; exports.readLockAsync = readLockAsync; /** * Take a write lock that will be released when the function has finished running * @param func * @param timeout time in ms to wait to get the lock. Null mean infinite. */ const writeLockAsync = (func, timeout = null) => { let options = {}; if (timeout != null) { options = { timeout }; } return new Promise((resolve, reject) => { lock.writeLock(async (release) => { try { const result = await func(); resolve(result); } catch (e) { reject(e); } finally { release(); } }, { ...options, timeoutCallback() { reject(new Error_1.TimeoutError("Timeout", 100)); } }); }); }; exports.writeLockAsync = writeLockAsync; //# sourceMappingURL=Lock.js.map