Question 14
Question
How would you check if a value is a promise in JavaScript?
Answer
Here's how you can determine if a value is a Promise in JavaScript:
function isPromise(value) {
return typeof value === 'object' && value !== null &&
typeof value.then === 'function';
}Explanation:
typeof value === 'object' && value !== null: This part ensures we're dealing with an object, not a primitive type like a number or string. It also excludesnull.typeof value.then === 'function': The key check! Promises have a.then()method that is used to handle their resolution or rejection. If this method exists and is a function, we've likely found a Promise.
Important Notes:
This method works reliably for standard Promises created with
new Promise().Some libraries might implement custom Promise-like objects. The above check should catch most common cases, but it might not cover every edge case.
Last updated