"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.requestLock = void 0;
var _Deferred = require("./Deferred");
var deferredMap = new WeakMap();

/**
 * Creates a deferred lock on the given object in order to sync critical blocks with race conditions.
 * Usage:
 *  releaseLock = await requestLock(obj);
 *  // do the critical actions in between
 *  releaseLock(); // important: always call this at the end of the critical block
 * Since it has to be used with the await keyword, it can guarantee that the block after the await requestLock(obj)
 * will be executed only if the concurrent lock was released.
 * @param object
 * @return {Promise<function(): *>}
 */
var requestLock = exports.requestLock = function requestLock(object) {
  var deferred = new _Deferred.Deferred();
  var prev = deferredMap.get(object);
  deferredMap.set(object, deferred);
  return new Promise(function (resolve) {
    if (prev) {
      prev.then(function () {
        resolve(deferred.resolve);
      });
    } else {
      resolve(deferred.resolve);
    }
  });
};