Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell if an object is a Promise?

Whether it's an ES6 Promise or a bluebird Promise, Q Promise, etc.

How do I test to see if a given object is a Promise?

like image 263
theram Avatar asked Jan 02 '15 17:01

theram


People also ask

What is a promise object?

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. To learn about the way promises work and how you can use them, we advise you to read Using promises first.

What is promise object write with example?

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. var promise = new Promise(function(resolve, reject) { // do thing, then…

How do you know if a promise is resolved?

The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.


2 Answers

How a promise library decides

If it has a .then function - that's the only standard promise libraries use.

The Promises/A+ specification has a notion called thenable which is basically "an object with a then method". Promises will and should assimilate anything with a then method. All of the promise implementation you've mentioned do this.

If we look at the specification:

2.3.3.3 if then is a function, call it with x as this, first argument resolvePromise, and second argument rejectPromise

It also explains the rationale for this design decision:

This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.

How you should decide

You shouldn't - instead call Promise.resolve(x) (Q(x) in Q) that will always convert any value or external thenable into a trusted promise. It is safer and easier than performing these checks yourself.

really need to be sure?

You can always run it through the test suite :D

like image 64
Benjamin Gruenbaum Avatar answered Oct 12 '22 10:10

Benjamin Gruenbaum


Checking if something is promise unnecessarily complicates the code, just use Promise.resolve

Promise.resolve(valueOrPromiseItDoesntMatter).then(function(value) {  }) 
like image 34
Esailija Avatar answered Oct 12 '22 10:10

Esailija