How to Execute Promise Only Once - Memoizing Promise

January 11, 2023

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("https://randomuser.me/api/");
    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.

memoized promise

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

Happy promise caching!

Reference


👋 I'm Ashik Nesin • Principal Software Engineer 👨‍💻• I write about web development and share insights into the behind-the-scenes of the projects that I'm building.

© 2023 Nesin Technologies LLP