Published on

How to Execute Promise Only Once - Memoizing Promise


At times, there might be an use case in which you'll need to request an API call or resolve a Promise only once for performance reason and serve the result in the subsequent calls to that promise.

For such use cases, we can follow the memoization technique

What's memoization?

Memoization is an optimization technique that is used to store the result in cache and then retrieve the result from cache for the subsequent reads instead of performing the operation again and again. Saving you the time that is needed for the computation.

How do I memoization a Promise?

Here is an example a little snippet on how to do it

function onlyExecuteOnce(fn) {
  let promise;
  let hasExecuted = false;
  return function() {
    if (!hasExecuted) {
      promise = fn().then((result) => {
        console.log('Fetching from API');
        hasExecuted = true;
        return result;
      }).catch((error) => {
        hasExecuted = false;
        throw error;
    } else {
        console.log('Cache hit: Data from Cache');
    return promise;

const myMemoizedPromise = onlyExecuteOnce(async () => {
    const response = await fetch("");
    const user = response.json();
    return user

myMemoizedPromise().then(data => console.log(data))

For the above snippet it'll fetch the actual API only once and cache it and then all the subsequent call will return the response of that cached API.

If you've more advanced use case, then check out Sindre Sorhus's p-memoize library.

Happy promise caching!