bitcore-wallet-service/lib/locallock.js

35 lines
577 B
JavaScript
Raw Normal View History

2015-04-07 13:02:08 -07:00
var _ = require('lodash');
var $ = require('preconditions').singleton();
var locks = {};
2015-04-08 06:21:01 -07:00
function Lock() {
2015-04-07 13:02:08 -07:00
};
2015-04-08 06:21:01 -07:00
Lock.prototype._runOne = function(token) {
var self = this;
if (locks[token].length == 0) return;
var task = locks[token][0];
task(null, function() {
locks[token].shift();
self._runOne(token);
});
2015-04-07 13:02:08 -07:00
};
2015-04-08 06:21:01 -07:00
Lock.prototype.locked = function(token, wait, max, task) {
if (_.isUndefined(locks[token])) {
locks[token] = [];
2015-04-07 13:02:08 -07:00
}
2015-04-08 06:21:01 -07:00
locks[token].push(task);
if (locks[token].length == 1) {
this._runOne(token);
2015-04-07 13:02:08 -07:00
}
};
module.exports = Lock;