JavaScript: Checking if a value is a Promise/thenable object
đ Wiki page | đ Last updated: Jan 27, 2023A common way to check if a value is a Promise in JavaScript is to use the instanceof
operator:
obj instanceof Promise
This will only work if an object is an instance of a native Promise class, but we can use any object that implements the then
method in place of a Promise, for example:
let x = {then: cb => cb(42)}
console.log(x instanceof Promise)
One option is to turn the thenable object to a native Promise with Promise.resolve
, which will always return the instance of Promise:
console.log(Promise.resolve(x) instance of Promise)
Or, we can just check that the value is an object that has the then
method:
function isPromise(v) {
return typeof v == "object" && typeof v.then == "function"
}
A few tests that everything is working as expected:
assert(isPromise(Promise.resolve(14)))
assert(isPromise({then: cb => cb(42)}))
assert(!isPromise(42))
assert(!isPromise({then: 42}))
Ask me anything / Suggestions
If you find this site useful in any way, please consider supporting it.