In JavaScript, Promises are objects that link the producing and the consuming code together. While in simple terms a Promise in JavaScript means the same as a promise in real life. Whenever a Promise is created there are 3 conditions or would rather say results that we can expect:
- resolve
- reject
- pending
As the above names suggest, whenever a Promise is created, we either get the Promise fulfilled, i.e. the Promise is resolved, or if we don’t get the result as expected, i.e. the Promise doesn’t get fulfilled, it is rejected. And the state during which the promise is neither being resolved nor rejected is called pending.
Syntax:
var promise = new Promise(function(resolve, reject) { (the producing code) });
In this article, we are going to identify if a JavaScript object is a Promise or not. Now there are many ways by which we can identify the same, let us see what are they and how we can easily identify a Promise.
Approach:
- Take a set of variables and objects.
- Pass those values to a function isPromise() which actually checks different conditions and identifies a Promise.
Method 1: By using typeof operator.
Example:
Javascript
<script> //Checking for a promise var prom = new Promise( function (resolve, reject) { resolve(); }); var num = 10; var name = "neveropen" ; var object = { site: "neveropen" }; console.log(isPromise(prom)); console.log(isPromise(num)); console.log(isPromise(name)); console.log(isPromise(object)); function isPromise(p) { return Boolean(p && typeof p.then === "function" ); } </script> |
Output:
true false false false
Method 2: By checking if the passed value p is an object and checking if p.then() is a function.
Example:
Javascript
<script> // Checking for a promise var prom = new Promise( function (resolve, reject) { resolve(); }); var num = 10; var name = "neveropen" ; var object = { site: "neveropen" }; console.log(isPromise(prom)); console.log(isPromise(num)); console.log(isPromise(name)); console.log(isPromise(object)); function isPromise(p) { return !!p && ( typeof p === 'object' || typeof p === 'function' ) && typeof p.then === 'function' ; } </script> |
Output:
true false false false
Method 3: By checking if Promise.resolve(p) == p.
Example:
Javascript
<script> // Checking for a promise var prom = new Promise( function (resolve, reject) { resolve(); }); var num = 10; var name = "neveropen" ; var object = { site: "neveropen" }; console.log(isPromise(prom)); console.log(isPromise(num)); console.log(isPromise(name)); console.log(isPromise(object)); function isPromise(p) { if (Promise && Promise.resolve) { return Promise.resolve(p) == p; } } </script> |
Output:
true false false false