UNPKG

@aws-amplify/core

Version:
1 lines 3.96 kB
{"version":3,"file":"Mutex.mjs","sources":["../../../src/Mutex/Mutex.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/*!\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Christian Speckner <cnspeckn@googlemail.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nexport class Mutex {\n constructor() {\n this._queue = [];\n this._pending = false;\n }\n isLocked() {\n return this._pending;\n }\n acquire() {\n const ticket = new Promise(resolve => this._queue.push(resolve));\n if (!this._pending) {\n this._dispatchNext();\n }\n return ticket;\n }\n runExclusive(callback) {\n return this.acquire().then(release => {\n let result;\n try {\n result = callback();\n }\n catch (e) {\n release();\n throw e;\n }\n return Promise.resolve(result).then((x) => {\n release();\n return x;\n }, e => {\n release();\n throw e;\n });\n });\n }\n _dispatchNext() {\n if (this._queue.length > 0) {\n this._pending = true;\n this._queue.shift()(this._dispatchNext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