Determine se o objeto é um objeto Promise

método um

Converta os objetos recebidos em Promiseobjetos e julgue se são iguais. Se forem iguais, significa que são Promiseobjetos.

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

Acho que você gosta

Origin blog.csdn.net/m0_53808238/article/details/130494497
Recomendado
Clasificación