javascriptasync-awaitcacheapi

Map.get() returns undefined inside async function


I want to get a list of all the different caches existing in the Cache API and how many assets each cache has. Even though I have managed to return the Map object with the info, when calling Map.get(cacheName) I get undefined.

I've seen that once the page has loaded, if I manually run 'cacheInfo = getCacheInfo()', then the cacheInfo.get() works.

function getCacheInfo() {
  const cacheMap = new Map();
  window.caches.keys().then(function(cacheNames) {
    cacheNames.forEach(function(cacheName) {
      window.caches
        .open(cacheName)
        .then(function(cache) {
          cacheMap.set(cacheName, 0);
          return cache.keys();
        })
        .then(function(requests) {
          requests.forEach(function(request) {
            cacheMap.set(cacheName, cacheMap.get(cacheName) + 1);
          });
        });
    });
  });
  return cacheMap;
}

async function printTable() {
  const cacheInfo = await getCacheInfo();
  console.log(cacheInfo);
  console.log(cacheInfo.get('html-cache')); // Returns undefined
}

printTable();

Solution

  • You mix async/await with .then syntaxes, for what? Best practice is just using async/await or Promise solving syntax, not both.

    For your case, I think async/await is a best choice, I convert your code to use async/await syntax. I think you need (maybe) read more about Promise, async/await to understand them.

    async function getCacheInfo() {
      const cacheMap = new Map();
      const cacheNames = await window.caches.keys();
      for (const cacheName of cacheNames) {
        const cache = await window.caches.open(cacheName);
        cacheMap.set(cacheName, 0);
    
        const requests = await cache.keys();
        requests.forEach((request) => {
          cacheMap.set(cacheName, cacheMap.get(cacheName) + 1);
        });
      }
      return cacheMap;
    }
    
    async function printTable() {
      const cacheInfo = await getCacheInfo();
      console.log(cacheInfo);
      console.log(cacheInfo.get('html-cache')); // Returns undefined
    }
    
    (async () => {
      await printTable();
    })();