Skip to content

Commit

Permalink
Method lock class added
Browse files Browse the repository at this point in the history
  • Loading branch information
Martin Krcmar committed Dec 17, 2018
1 parent 4eeca10 commit 303f056
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
3 changes: 2 additions & 1 deletion appmixer-lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ module.exports = {
db: require('./db/db'),
redis: require('./db/redis'),
lock: {
mutex: require('./lock/mutex')
mutex: require('./lock/mutex'),
method: require('./lock/method')
},
util: {
array: require('./util/array'),
Expand Down
48 changes: 48 additions & 0 deletions lock/method.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
'use strict';
const Promise = require('bluebird');
const check = require('check-types');

/**
* This class provides func to execute function only once (when called multiple times from
* various resources) and return the same result to all callers.
*/
class Method {

constructor() {

this.inProgress = false;
this.callbacks = [];
}

/**
* @param {function} func
* @return {Promise<void>}
* @public
*/
async call(func) {

check.assert.function(func, 'Invalid function.');

if (this.inProgress) {
return new Promise((resolve, reject) => {
this.callbacks.push({ resolve, reject });
});
}

try {
this.inProgress = true;
const result = await func();
this.inProgress = false;
while (this.callbacks.length > 0) {
this.callbacks.pop().resolve(result);
}
} catch (err) {
this.inProgress = false;
while (this.callbacks.length > 0) {
this.callbacks.pop().reject(err);
}
}
}
}

module.exports = Method;

0 comments on commit 303f056

Please sign in to comment.