Sohaib Farooqi Sohaib Farooqi - 10 months ago 53
Node.js Question

Issue with conditionally returning promise (Nodejs)

Title of this question might needs editing

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

function getAllTypes()
return from_cache;

// db Query
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?


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