método um
Converta os objetos recebidos em Promise
objetos e julgue se são iguais. Se forem iguais, significa que são Promise
objetos.
function isPromise(obj) {
if (Promise && Promise.resolve) {
return Promise.resolve(obj) == obj
} else {
throw new Error('当前环境不支持 Promise !')
}
}
Método dois
Determine se o protótipo do objeto é uma string "[object Promise]"
.
function isPromise(obj) {
return obj && Object.prototype.toString.call(obj) === '[object Promise]'
}
exemplo de erro
Promise tem um método then para determinar se o objeto tem um método then.
Razão do erro: Se houver um atributo then em um objeto e o atributo for uma função, o julgamento falhará.
function isPromise(obj) {
return obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}
const obj = {
then: function() {
console.log('我不是 Promise 对象');
}
}
FIM