-
Notifications
You must be signed in to change notification settings - Fork 0
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
Benjamin Strauß
committed
Jan 9, 2018
1 parent
b4b19d9
commit b924995
Showing
1 changed file
with
44 additions
and
0 deletions.
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
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}; |