Check if an Object is a Promise in JavaScript

Are you stuck in a scenario in your code where you have to check if an Object in your code is a Promise object or not?

Here are some methods to check if an Object is a Promise object.

Method 1 : Checking if Object.prototype.toString.call(p) === "[object Promise]"

function isPromise(p) {
  return p && Object.prototype.toString.call(p) === "[object Promise]";
}
// Tests
var pi = 3.14;
var name = "Satvik";
var obj = { site: "debugpointer.com" };
var numbers = [1, 2, 3];
var prom = new Promise(function(resolve, reject) {
  resolve();
});

isPromise(pi); // false
isPromise(name); // false
isPromise(obj); // false
isPromise(numbers); // false
isPromise(prom); // true

Method 2 : Checking if typeof value.then === 'function'

function isPromise(value) {
  return Boolean(value && typeof value.then === "function");
}
// Tests
var pi = 3.14;
var name = "Satvik";
var obj = { site: "debugpointer.com" };
var numbers = [1, 2, 3];
var prom = new Promise(function(resolve, reject) {
  resolve();
});

isPromise(pi); // false
isPromise(name); // false
isPromise(obj); // false
isPromise(numbers); // false
isPromise(prom); // true

Source - https://github.com/graphql/graphql-js/blob/master/src/jsutils/isPromise.js

Method 3 : Checking if Promise.resolve(object) == object

Here is a very modular way, where you can use the function isPromise to achieve it-

function isPromise(object) {
  if (Promise && Promise.resolve) {
    return Promise.resolve(object) == object;
  } else {
    throw "Promise not supported in your environment"; // Most modern browsers support Promises
  }
}
// Tests
var pi = 3.14;
var name = "Satvik";
var obj = { site: "debugpointer.com" };
var numbers = [1, 2, 3];
var prom = new Promise(function(resolve, reject) {
  resolve();
});

isPromise(pi); // false
isPromise(name); // false
isPromise(obj); // false
isPromise(numbers); // false
isPromise(prom); // true

Credits - https://gist.github.com/MarkoCen/ec27b8cd42855fde8a245d43b7b081d0

Method 4 : Checking if obj is Object & obj.then is a function

function isPromise(obj) {
  return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}
// Tests
var pi = 3.14;
var name = "Satvik";
var obj = { site: "debugpointer.com" };
var numbers = [1, 2, 3];
var prom = new Promise(function(resolve, reject) {
  resolve();
});

isPromise(pi); // false
isPromise(name); // false
isPromise(obj); // false
isPromise(numbers); // false
isPromise(prom); // true