Friday, 23 August, 2019 UTC


Summary

Async can throw a real wrench into the cogs of our programming workflows, all despite the fact that async is the modern JavaScript pattern. While async/await helps, there’s sometimes confusion about the way to have a single function that returns a value whether it exists or needs a Promise to retrieve.
The key thing to remember is that functions declared as async automatically return a Promise, so you don’t need explicity return the existing content with Promise.resolve(content):
async function getValueOrFetch(ojbOrInfo) {
  // If the value exists, immediately return it
  if(ojbOrInfo) {
    return ojbOrInfo;
  }
  // Return the promise-based info
  return asyncFunctionToGetInfo(ojbOrInfo);
}
Let’s look at a real life example: returning cached contents instead of doing a fetch call to retrieve them:
const cache = {
  /* url: content */
};

// Async function that returns cached content or retrieves fresh content
async function getInfo(url) {
  // Check for value in cache
  if (cache[url]) {
    // Return the content, no need for Promise.resolve
    return cache[url];
  }
  // Get the content fresh
  const content = await fetch("https://www.facebook.com").then(r => r.text());
  cache[url] = content;
  return content;
}
My main goal with this post is making you understand that return Promise.resolve(data) isn’t needed with async functions — you can simply return the value and it will be wrapped in a promise!
The post Promises and Static Values appeared first on David Walsh Blog.