Skip to content

Commit

Permalink
feature(functions): cacheAsyncValue
Browse files Browse the repository at this point in the history
  • Loading branch information
Benjamin Strauß committed Jan 9, 2018
1 parent b4b19d9 commit b924995
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/functions/functions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
goog.module('clulib.functions');

/**
* Creates an async function that runs the provided parameter 'func'
* async function only once.
*
* When called for the first time, the given async function is called
* and its returned result or error is cached. Subsequent calls will
* return the cached result or error.
*
* @param {function():Promise<T>} func
* @returns {function():Promise<T>}
* @template T
*/
function cacheAsyncValue (func) {
let done = false;
let isError = false;

/**
* @type {T}
*/
let result = null;
let error = null;

return async function () {
if (!done) {
try {
result = await func();
} catch (e) {
error = e;
isError = true;
} finally {
done = true;
}
}

if (isError)
throw error;
else
return result;
};
}

exports = {cacheAsyncValue};

0 comments on commit b924995

Please sign in to comment.