UNPKG

2.58 kBJavaScriptView Raw
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3/*!
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2016 Christian Speckner <cnspeckn@googlemail.com>
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26var Mutex = /** @class */ (function () {
27 function Mutex() {
28 this._queue = [];
29 this._pending = false;
30 }
31 Mutex.prototype.isLocked = function () {
32 return this._pending;
33 };
34 Mutex.prototype.acquire = function () {
35 var _this = this;
36 var ticket = new Promise(function (resolve) {
37 return _this._queue.push(resolve);
38 });
39 if (!this._pending) {
40 this._dispatchNext();
41 }
42 return ticket;
43 };
44 Mutex.prototype.runExclusive = function (callback) {
45 return this.acquire().then(function (release) {
46 var result;
47 try {
48 result = callback();
49 }
50 catch (e) {
51 release();
52 throw e;
53 }
54 return Promise.resolve(result).then(function (x) { return (release(), x); }, function (e) {
55 release();
56 throw e;
57 });
58 });
59 };
60 Mutex.prototype._dispatchNext = function () {
61 if (this._queue.length > 0) {
62 this._pending = true;
63 this._queue.shift()(this._dispatchNext.bind(this));
64 }
65 else {
66 this._pending = false;
67 }
68 };
69 return Mutex;
70}());
71export default Mutex;