-3

I have a situation where I need to check if a function returns a promise, the problem is, its a browser implemented function and some browsers DO return a promise and some don't. I was checking: How do I tell if an object is a Promise?, to see how to check if a function returns a promise and it recommends using Promise.resolve(). But what exactly happens when you call Promise.resolve() on a non-promisified function?

I tried reading this, but i wasn't able to find an answer to the question exactly: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve

Matt Pengelly
  • 1,480
  • 2
  • 20
  • 34
  • *" otherwise the returned promise will be fulfilled with the value."*. Yes you can use it. Note that you could simply have tested. – Denys Séguret Jun 12 '18 at 14:38

2 Answers2

4

From the MDN documentation:

returns a Promise object that is resolved with the given value. If the value is a promise, that promise is returned; if the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable.

So yeah wrapping that returned value with Promise.resolve would take care of promisifying that value.

J. Pichardo
  • 3,077
  • 21
  • 37
1

You can assign what the function returns to a variable and then evaluate that variable like so:

var obj = whateverFunction();

if(typeof obj.then === "function"){
   // This is a promise because it has a then function
}

Although I suspect the answer using Promise.resolve might be better.