InterviewHubPRO
Section Overview
Q419

Question 419 of 521

Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)

80%
JavaScript Internals (521 Qs)•Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)

How do you check an object is a promise or not

If you don't know if a value is a promise or not, wrapping the value as Promise.resolve(value) which returns a promise

javascript
 function isPromise(object) {
   if (Promise && Promise.resolve) {
     return Promise.resolve(object) == object;
   } else {
     throw "Promise not supported in your environment";
   }
 }

 var i = 1;
 var promise = new Promise(function (resolve, reject) {
   resolve();
 });

 console.log(isPromise(i)); // false
 console.log(isPromise(promise)); // true

Another way is to check for .then() handler type

javascript
 function isPromise(value) {
   return Boolean(value && typeof value.then === "function");
 }
 var i = 1;
 var promise = new Promise(function (resolve, reject) {
   resolve();
 });

 console.log(isPromise(i)); // false
 console.log(isPromise(promise)); // true