DEV Community

Discussion on: What is not right in this code? Post your solution.

Collapse
 
pichardoj profile image
J. Pichardo

Well besides this line ...


cache.set("file2, 'data of file 2...");

// Should be (Note: quotes)

cache.set("file2", "data of file 2...");

This are the changes I'd make

  1. Use object instead of Map (Easier to have immutable structures)
  2. Wrap cache in a Promise.resolve in order to reuse code and be able to use a ternary operator
  3. For consistency DO NOT use a callback syntax for a promise based function

So, the final script would be:


const cache = {
  ["file1"]: "data of file 1...",
  ["file2"]: "data of file 2..."
};

const getFile = fileName => {

  // Wrap the cache in a promise in order to do chaining;
  const cachePromise =
    cache[filename] != null
      ? Promise.resolve(cache)
      : readFilePromise(fileName).then(
          content => (cache = { ...cache, [fileName]: content })
        );

  // Return a promise with the data
  return cachePromise.then(cache => cache[fileName]);
};

// DO NOT pass a callback.
getFile("file1")
  .then(data => {
    // Do Something
  })
  .catch(err => {
    // Do Something else
  });