How to Check if a Value is a Promise in JavaScript ?
Last Updated :
29 Jan, 2024
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;
}
const myPromise = new Promise((resolve, reject) => {
resolve( 'Success!' );
});
const notAPromise = 'Hello, I am not a Promise!' ;
console.log(isPromise(myPromise));
console.log(isPromise(notAPromise));
|
Share your thoughts in the comments
Please Login to comment...