Skip to content

Instantly share code, notes, and snippets.

@Vintharas
Last active January 22, 2016 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vintharas/9bfb84ef68aa9e59a5b5 to your computer and use it in GitHub Desktop.
Save Vintharas/9bfb84ef68aa9e59a5b5 to your computer and use it in GitHub Desktop.
Memoize using a promise (angular $q)
/*
*
* Memoizes call to a service using a promise
*
*/
function memoizeWithPromise(getFn) {
let memoizedCalls = new Map();
return function(...args) {
let serializedArgs = JSON.stringify(args);
if (memoizedCalls.has(serializedArgs)) {
return memoizedCalls.get(serializedArgs);
} else {
let promise = getFn(...args);
memoizedCalls.set(serializedArgs, promise);
return promise;
// also
// let promise = $q.when(getFn(...args));
// memoizedCalls.set(serializedArgs, promise);
// return promise;
// http://www.bennadel.com/blog/2735-q-when-is-the-missing-q-resolve-method-in-angularjs.htm
}
}
}
@Vintharas
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment