Convert Lock.js to ts

This commit is contained in:
RMidhunSuresh 2021-11-16 15:06:19 +05:30
parent a3460d8c2a
commit c8eb7ea7ac
3 changed files with 14 additions and 16 deletions

View file

@ -16,7 +16,7 @@ limitations under the License.
import {DecryptionError} from "../common.js"; import {DecryptionError} from "../common.js";
import {groupBy} from "../../../utils/groupBy"; import {groupBy} from "../../../utils/groupBy";
import {MultiLock} from "../../../utils/Lock.js"; import {MultiLock} from "../../../utils/Lock";
import {Session} from "./Session.js"; import {Session} from "./Session.js";
import {DecryptionResult} from "../DecryptionResult.js"; import {DecryptionResult} from "../DecryptionResult.js";

View file

@ -15,12 +15,10 @@ limitations under the License.
*/ */
export class Lock { export class Lock {
constructor() { private _promise: Promise<void> | null = null;
this._promise = null; private _resolve: (() => void) | null = null;
this._resolve = null;
}
tryTake() { tryTake(): boolean {
if (!this._promise) { if (!this._promise) {
this._promise = new Promise(resolve => { this._promise = new Promise(resolve => {
this._resolve = resolve; this._resolve = resolve;
@ -30,17 +28,17 @@ export class Lock {
return false; return false;
} }
async take() { async take(): Promise<void> {
while(!this.tryTake()) { while(!this.tryTake()) {
await this.released(); await this.released();
} }
} }
get isTaken() { get isTaken(): boolean {
return !!this._promise; return !!this._promise;
} }
release() { release(): void {
if (this._resolve) { if (this._resolve) {
this._promise = null; this._promise = null;
const resolve = this._resolve; const resolve = this._resolve;
@ -49,17 +47,17 @@ export class Lock {
} }
} }
released() { released(): Promise<void> | null {
return this._promise; return this._promise;
} }
} }
export class MultiLock { export class MultiLock {
constructor(locks) {
this.locks = locks; constructor(public readonly locks: Lock[]) {
} }
release() { release(): void {
for (const lock of this.locks) { for (const lock of this.locks) {
lock.release(); lock.release();
} }
@ -86,9 +84,9 @@ export function tests() {
lock.tryTake(); lock.tryTake();
let first; let first;
lock.released().then(() => first = lock.tryTake()); lock.released()!.then(() => first = lock.tryTake());
let second; let second;
lock.released().then(() => second = lock.tryTake()); lock.released()!.then(() => second = lock.tryTake());
const promise = lock.released(); const promise = lock.released();
lock.release(); lock.release();
await promise; await promise;

View file

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import {Lock} from "./Lock.js"; import {Lock} from "./Lock";
export class LockMap { export class LockMap {
constructor() { constructor() {