DEV Community

Luka Vidaković
Luka Vidaković

Posted on • Originally published at lvidakovic.com

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:

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!
})
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (2)

Collapse
 
seanmclem profile image
Seanmclem

why use setTimeout?

Collapse
 
apisurfer profile image
Luka Vidaković

Good point. It was meant to be something that mimics asynchronous data fetching. Now I see it's confusing, especially without the specified time.
In this case, it can easily be replaced with the following to still prove the same point:

function getDataAsync() {
  return Promise.resolve(data)
}