method one
Convert the incoming objects into Promise
objects, and judge whether they are equal. If they are equal, it means that they are Promise
objects.
function isPromise(obj) {
if (Promise && Promise.resolve) {
return Promise.resolve(obj) == obj
} else {
throw new Error('当前环境不支持 Promise !')
}
}
Method Two
Determine whether the object prototype is a string "[object Promise]"
.
function isPromise(obj) {
return obj && Object.prototype.toString.call(obj) === '[object Promise]'
}
error example
Promise has a then method to determine whether the object has a then method.
Error reason: If there is a then attribute in an object, and the attribute is a function, the judgment will fail.
function isPromise(obj) {
return obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}
const obj = {
then: function() {
console.log('我不是 Promise 对象');
}
}
END