Promise.resolve() everything

Ever had a block of code that, based on a condition can fetch data asynchronosuly or synchronously?

In one case you’ll need to wait for the results, and in the other the results will be available at the very next “line”.

Simple trick that circles around the internet every once in a while, but is underutilized by many developers:

const data = 'test'

// synchronous
function getData() {
  return data
}

// asynchronous
function getDataAsync() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(data))
  })
}

let response

// let's imagine we are fetching data based on environment variable
if (ENV_ASYNC) {
  response = getDataAsync()
} else {
  response = getData()
}

// you can see in one case response is a promise and in the other it's the data itself
// how to handle both in unified way? Use Promise.resolve

Promise.resolve(response).then(responseData => {
  // collect money here! we get the extracted data!
})

If you can’t understand this completely look up on how Promises work with returns and especially cases when you return nothing(undefined), data reference, or another promise.

Cheers!