How to Check if a Value is a Promise in JavaScript ?
To check if a value is a Promise in JavaScript, we can use the instanceof
operator. Promises are a specific type of object, and this operator allows you to check if an object is an instance of a particular class or constructor function. so we will use this to check whether the given value is a promise or not.
Example: Here, the isPromise
function checks if the provided value is an instance of the Promise
constructor. It returns true
if it is and false
otherwise.
Javascript
function isPromise(value) { return value instanceof Promise; } // Example usage: const myPromise = new Promise((resolve, reject) => { // Some asynchronous operation resolve( 'Success!' ); }); const notAPromise = 'Hello, I am not a Promise!' ; console.log(isPromise(myPromise)); // true console.log(isPromise(notAPromise)); // false |
Output
true false