Yalda Yalda - 5 months ago 7
Node.js Question

My function could return a promise or value, how to avoid it?

I think it's bad practice to have different return types. So, this is my function, and I want it to always return a promise.

I tried to simplify the scenario. Let's say I have two lines of products (line X and line Y) and the way I'm retrieving a product by name, from each line is totally different from the other.

Please also note that ideally, I wanted to have a function to "or" two promises and return whichever that resolves successfully. But I couldn't think of a better way to achieve this!

ProductService.findProductByName = function findProductByName(name) {
return LineXService.findOneByName(name) // promise
.then(function _returnProduct(product) {
return product
? product // value
: LineYService.findOneByName(name)); // promise
})
};

Answer

You're right that returning a consistent thing is better than an ambiguous result. Normally you can cast an arbitrary value into a promise easily enough. For example using resolve:

if (product) {
  return Promise.resolve(product);
}

return LineYService.findOneByName(name);

It's worth noting, as Kevin B observes, that this is irrelevant in this particular case since your outer function always returns a promise. The need to promisify a value is only a concern if this is not part of a surrounding promise.