Determine whether the object is a Promise object

method one

Convert the incoming objects into Promiseobjects, and judge whether they are equal. If they are equal, it means that they are Promiseobjects.

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

Guess you like

Origin blog.csdn.net/m0_53808238/article/details/130494497
Recommended