Sohaib Farooqi Sohaib Farooqi - 6 months ago 18
Node.js Question

Issue with conditionally returning promise (Nodejs)

Title of this question might needs editing

Hi,
I have a method which either return an object or a promise. The function is as follows:

function getAllTypes()
{
if(cache_hit)
return from_cache;

else
{
// db Query
findAllTypes.then(function(result){
return result;
}
}
}


This function will either returns a promise or a plain JS object depending on case. This is a utility function and will going to be used in many different places. I would like to keep its return type constant i.e either a promise or plain JS object(Which don't needs to be resolved) in both cases.

Is there a way to accomplish this?

Answer

If your method might do something async then assume that it'll do it which means that it'll always return a promise, you can create a Promise from a single value with Promise.resolve i.e

function getAllTypes() {
  if (cache_hit) return Promise.resolve(from_cache)
  return findAllTypes() // which returns a promise
}