Promise finally实现

2022-01-03  本文已影响0人  湘兰沅芷
const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected'// 失败
class MyPromise {
  constructor(executor) {
    // 捕获执行器错误
    try{
      executor(this.resolve, this.reject)
    } catch (e) {
      this.reject(e)
    }
  }
  status = PENDING
  value = undefined
  reason = undefined
  successCallback = []
  failCallback = []
  resolve = value => {
    if (this.status !== PENDING) return
    // 将状态修改为成功
    this.status = FULFILLED
    // 保存成功之后的值
    this.value = value
    // this.successCallback && this.successCallback(this.value)
    while(this.successCallback.length) {
      this.successCallback.shift()()
    }
  }
  reject = reason => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = reason
    // this.failCallback && this.failCallback(this.reason)
    while(this.failCallback.length) {
      this.failCallback.shift()()
    }
  }
  then(successCallback, failCallback) {
    successCallback = successCallback ? successCallback : value => value 
    failCallback = failCallback ? failCallback : reason => {throw reason}
    let promise2 = new MyPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value)
            // 判断x的值是普通值还是promise对象
            // 如果是普通值,直接调用resolve
            // 如果是promise对象,查看promise对象返回的结果
            // 再根据promise对象返回的结果,决定调用resolve还是reject
            resolvePromise(promise2, x, resolve, reject)
          } catch(e) {
            reject(e)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason)
            // 判断x的值是普通值还是promise对象
            // 如果是普通值,直接调用resolve
            // 如果是promise对象,查看promise对象返回的结果
            // 再根据promise对象返回的结果,决定调用resolve还是reject
            resolvePromise(promise2, x, resolve, reject)
          } catch(e) {
            reject(e)
          }
        }, 0)
      } else {
        // 等待
        // 讲成功回调和失败回调进行存储
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value)
              // 判断x的值是普通值还是promise对象
              // 如果是普通值,直接调用resolve
              // 如果是promise对象,查看promise对象返回的结果
              // 再根据promise对象返回的结果,决定调用resolve还是reject
              resolvePromise(promise2, x, resolve, reject)
            } catch(e) {
              reject(e)
            }
          }, 0)
        })
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason)
              // 判断x的值是普通值还是promise对象
              // 如果是普通值,直接调用resolve
              // 如果是promise对象,查看promise对象返回的结果
              // 再根据promise对象返回的结果,决定调用resolve还是reject
              resolvePromise(promise2, x, resolve, reject)
            } catch(e) {
              reject(e)
            }
          }, 0)
        })
      }
    })
    return promise2
  }
  finally (callback) {
    return this.then(value => {
      return MyPromise.resolve(callback()).then(() => value)
    }, reason => {
      return MyPromise.resolve(callback()).then(() => {throw reason})
    })
  }
  static all (array) {
    let result = [];
    let index = 0;
    
    return new MyPromise((resolve, reject) => {
      function addData(key, value) {
        result[key] = value;
        index++;
        if (index === array.length) {
          resolve(result);
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i];
        if (current instanceof MyPromise) {
          current.then(value => addData(i, value), reason => reject(reason))
        }else {
          addData(i, array[i]);
        }
      }
      // resolve(result)
    })
  }
  static resolve (value) {
    if (value instanceof MyPromise) return value;
    return new MyPromise(resolve => resolve(value))
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
   return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  }
  if (x instanceof MyPromise) {
    // x.then(value => resolve(value), reason => reject(reason))
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

module.exports = MyPromise

const MyPromise = require('./myPromise')

function p1 () {
return new MyPromise(function(resolve, reject) {
resolve('p1')
})
}
function p2 () {
return new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('p2')
}, 2000);
})
}
p2().finally(() => {
console.log('finally')
}).then(value => console.log(value), reason => console.log(reason))

catch的实现

const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected'// 失败
class MyPromise {
constructor(executor) {
// 捕获执行器错误
try{
executor(this.resolve, this.reject)
} catch (e) {
this.reject(e)
}
}
status = PENDING
value = undefined
reason = undefined
successCallback = []
failCallback = []
resolve = value => {
if (this.status !== PENDING) return
// 将状态修改为成功
this.status = FULFILLED
// 保存成功之后的值
this.value = value
// this.successCallback && this.successCallback(this.value)
while(this.successCallback.length) {
this.successCallback.shift()()
}
}
reject = reason => {
if (this.status !== PENDING) return
this.status = REJECTED
this.reason = reason
// this.failCallback && this.failCallback(this.reason)
while(this.failCallback.length) {
this.failCallback.shift()()
}
}
then(successCallback, failCallback) {
successCallback = successCallback ? successCallback : value => value
failCallback = failCallback ? failCallback : reason => {throw reason}
let promise2 = new MyPromise((resolve, reject) => {
if (this.status === FULFILLED) {
setTimeout(() => {
try {
let x = successCallback(this.value)
// 判断x的值是普通值还是promise对象
// 如果是普通值,直接调用resolve
// 如果是promise对象,查看promise对象返回的结果
// 再根据promise对象返回的结果,决定调用resolve还是reject
resolvePromise(promise2, x, resolve, reject)
} catch(e) {
reject(e)
}
}, 0)
} else if (this.status === REJECTED) {
setTimeout(() => {
try {
let x = failCallback(this.reason)
// 判断x的值是普通值还是promise对象
// 如果是普通值,直接调用resolve
// 如果是promise对象,查看promise对象返回的结果
// 再根据promise对象返回的结果,决定调用resolve还是reject
resolvePromise(promise2, x, resolve, reject)
} catch(e) {
reject(e)
}
}, 0)
} else {
// 等待
// 讲成功回调和失败回调进行存储
this.successCallback.push(() => {
setTimeout(() => {
try {
let x = successCallback(this.value)
// 判断x的值是普通值还是promise对象
// 如果是普通值,直接调用resolve
// 如果是promise对象,查看promise对象返回的结果
// 再根据promise对象返回的结果,决定调用resolve还是reject
resolvePromise(promise2, x, resolve, reject)
} catch(e) {
reject(e)
}
}, 0)
})
this.failCallback.push(() => {
setTimeout(() => {
try {
let x = failCallback(this.reason)
// 判断x的值是普通值还是promise对象
// 如果是普通值,直接调用resolve
// 如果是promise对象,查看promise对象返回的结果
// 再根据promise对象返回的结果,决定调用resolve还是reject
resolvePromise(promise2, x, resolve, reject)
} catch(e) {
reject(e)
}
}, 0)
})
}
})
return promise2
}
finally (callback) {
return this.then(value => {
return MyPromise.resolve(callback()).then(() => value)
}, reason => {
return MyPromise.resolve(callback()).then(() => {throw reason})
})
}
catch(failCallback) {
return this.then(undefined, failCallback)
}
static all (array) {
let result = [];
let index = 0;

return new MyPromise((resolve, reject) => {
  function addData(key, value) {
    result[key] = value;
    index++;
    if (index === array.length) {
      resolve(result);
    }
  }
  for (let i = 0; i < array.length; i++) {
    let current = array[i];
    if (current instanceof MyPromise) {
      current.then(value => addData(i, value), reason => reject(reason))
    }else {
      addData(i, array[i]);
    }
  }
  // resolve(result)
})

}
static resolve (value) {
if (value instanceof MyPromise) return value;
return new MyPromise(resolve => resolve(value))
}
}

function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
}
if (x instanceof MyPromise) {
// x.then(value => resolve(value), reason => reject(reason))
x.then(resolve, reject)
} else {
resolve(x)
}
}

module.exports = MyPromise

上一篇 下一篇

猜你喜欢

热点阅读