-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Martin Krcmar
committed
Dec 17, 2018
1 parent
4eeca10
commit 303f056
Showing
2 changed files
with
50 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |