静态方法Promise.rosolve()
用过这个方法的应该都知道:
- 这个方法的作用是将传入的参数转化成promise对象
- 如果参数是一个 Promise 实例,直接返回这个 Promise 实例
- 如果参数是一个 具有then方法的 thenable 对象,例如以下的对象,Promise.resolve() 方法会将这个对象转为 Promise 对象,然后立即执行 thenable 对象 then 方法
const thenable = {
then: function(resolve,reject){
resolve('ok')
}
}
- 传入的参数不是对象,或者不具有上面 then 方法的对象,那么 Promise.resolve() 方法返回个新的 Promise 实例,状态为已成功,并把参数传递出去
- 不带有任何参数,Promise.resolve() 方法允许在调用时不带有参数而直接返回个新的 Promise 实例,状态为已成功
基于以上用法,我们来实现一下这个方法
Promise.resolve = function(param){
// 如果传入的参数已经是个Promise对象了,直接返回这个对象
if(param instanceof Promise){
return param;
}
return new Promise((resolve,reject)=>{
//如果参数是一个 具有then方法的 thenable 对象 , 执行then方法
if(param && Object.prototype.toString.call(param) ===