复习之前的

catch方法

time 18m55s

  1. catch(onRejected) {
  2. return this.then(null, onRejected);
  3. }

resolve方法

time 20m03s
time 30
time 43m

测试方法

  1. const p1 = new MyPromise((resolve, reject) => {
  2. setTimeout(() => {
  3. reject('1000');
  4. }, 3000)
  5. })
  6. MyPromise.resolve(p1)
  7. .then(res => console.log(res, 'success')
  8. , err => console.log(err, 'fail')
  9. )

1000 fail

  1. /**
  2. * 判断值是否是promise对象,thanable对象
  3. * @param value 参数,在这里是回调函数,比如promise.resolve的参数,可能是函数,
  4. * 可能是promise对象
  5. * @returns {boolean} 是否是promise对象,thenable对象
  6. */
  7. const isPromsie = (value) => typeof value.then === "function";
  1. static resolve(value) {
  2. if (isPromsie(value)) {
  3. return value;
  4. } else {
  5. return new MyPromise((resolve, reject) => {
  6. resolve(value)
  7. })
  8. }
  9. }

当时promise对象时,返回promise对象value,当不是时返回经过包装的promise对象

  1. const p1 = new MyPromise((resolve, reject) => {
  2. setTimeout(() => {
  3. reject(new MyPromise((resolve, reject) => {
  4. setTimeout(()=>{
  5. reject('1000');
  6. },3000)
  7. }));
  8. }, 3000)
  9. })
  10. MyPromise.resolve(p1)
  11. .then(res => console.log(res, 'success')
  12. , err => console.log(err, 'fail')
  13. )
  1. static resolve(value) {
  2. return new MyPromise((resolve, reject) => {
  3. resolve(value)
  4. })
  5. }

把isPromsie放到resolve中

  1. let resolve = (value) => {
  2. if (this.state === 'pending') {
  3. /*time 43m*/
  4. if (isPromsie(value)) {
  5. /*递归调用,继续resolve,如果是reject走reject
  6. * value是promise,但最终还是得resolve或reject,所以得用then
  7. * 运行,为了运行resolve、或者reject,通过then取出promise对象value
  8. * 中的值,再进行resolve或者reject,reject是不能运行一个promise对象的*/
  9. value.then(data => resolve(data), err => reject(err));
  10. } else {
  11. this.state = 'fullFilled';
  12. this.value = value;
  13. // this.onFullFilledCallbacks.forEach(fn => fn(this.value));
  14. this.onFullFilledCallbacks.forEach(fn => fn());
  15. }
  16. }
  17. }

finally

time 49m