promise实现

179 阅读6分钟

状态改变

  • executor为执行者
  • 当执行者出现异常时触发拒绝状态
  • 使用静态属性保存状态值
  • 状态只能改变一次,所以在resolve与reject添加条件判断
  • 因为 resolve或rejected方法在executor中调用,作用域也是executor作用域,这会造成this指向window,现在我们使用的是class定义,this为undefined。
class ZX {
  static PENDING = "pending";
  static FULFILLED = "fulfilled";
  static REJECTED = "rejected";
  constructor(executor) {
    this.status = ZX.PENDING;
    this.value = null;
    try {
      executor(this.resolve.bind(this), this.reject.bind(this));
    } catch (error) {
      this.reject(error);
    }
  }
  resolve(value) {
    if (this.status == ZX.PENDING) {
      this.status = ZX.FULFILLED;
      this.value = value;
    }
  }
  reject(value) {
    if (this.status == ZX.PENDING) {
      this.status = ZX.REJECTED;
      this.value = value;
    }
  }
}

下面测试一下状态改变

<script src="ZX.js"></script>
<script>
  let p = new ZX((resolve, reject) => {
    resolve("success");
  });
  console.log(p);
</script>

THEN

现在添加then方法来处理状态的改变,有以下几点说明

  • then可以有两个参数,即成功和错误时的回调函数
  • then的函数参数都不是必须的,所以需要设置默认值为函数,用于处理当没有传递时情况
  • 当执行then传递的函数发生异常时,统一交给onRejected来处理错误

基础构建

then(onFulfilled, onRejected) {
  if (typeof onFulfilled != "function") {
    // 此处将值返回,解决 then 穿透问题
    onFulfilled = value => value;
  }
  if (typeof onRejected != "function") {
    onRejected = value => value;
  }
  if (this.status == ZX.FULFILLED) {
    try {
      onFulfilled(this.value);
    } catch (error) {
      onRejected(error);
    }
  }
  if (this.status == ZX.REJECTED) {
    try {
      onRejected(this.value);
    } catch (error) {
      onRejected(error);
    }
  }
}

下面来测试 then 方法,结果正常输出 success

let p = new ZX((resolve, reject) => {
  resolve("success");
}).then(
  value => {
    console.log(value);
  },
  reason => {
    console.log(reason);
  }
);

异步任务

但上面的代码产生的Promise并不是异步的,使用setTimeout来将onFulfilled与onRejected做为异步宏任务执行

then(onFulfilled, onRejected) {
  if (typeof onFulfilled != "function") {
    onFulfilled = value => value;
  }
  if (typeof onRejected != "function") {
    onRejected = value => value;
  }
  if (this.status == ZX.FULFILLED) {
    setTimeout(() => {
      try {
        onFulfilled(this.value);
      } catch (error) {
        onRejected(error);
      }
    });
  }
  if (this.status == ZX.REJECTED) {
    setTimeout(() => {
      try {
        onRejected(this.value);
      } catch (error) {
        onRejected(error);
      }
    });
  }
}

现在再执行代码,已经有异步效果了,先输出了 ZX,再输出 success

let p = new ZX((resolve, reject) => {
  resolve("success");
}).then(
  value => {
    console.log(value);
  },
  reason => {
    console.log(reason);
  }
);
console.log("ZX");

PENDING状态

目前then方法无法处理promise为pending时的状态

let p = new ZX((resolve, reject) => {
  setTimeout(() => {
    resolve("success");
  });
})

为了处理以下情况,需要进行几点改动

在构造函数中添加callbacks来保存pending状态时处理函数,当状态改变时循环调用

    constructor(executor) {
      ...
      this.callbacks = [];
      ...
    }    

将then方法的回调函数添加到 callbacks 数组中,用于异步执行

    then(onFulfilled, onRejected) {
      if (typeof onFulfilled != "function") {
        onFulfilled = value => value;
      }
      if (typeof onRejected != "function") {
        onRejected = value => value;
      }
    	if (this.status == ZX.PENDING) {
        this.callbacks.push({
          onFulfilled: value => {
            try {
              onFulfilled(value);
            } catch (error) {
              onRejected(error);
            }
          },
          onRejected: value => {
            try {
              onRejected(value);
            } catch (error) {
              onRejected(error);
            }
          }
        });
      }
      ...
    }

resovle 与 reject 中添加处理 callback 方法的代码

    resolve(value) {
      if (this.status == ZX.PENDING) {
        this.status = ZX.FULFILLED;
        this.value = value;
        this.callbacks.map(callback => {
          callback.onFulfilled(value);
        });
      }
    }
    reject(value) {
      if (this.status == ZX.PENDING) {
        this.status = ZX.REJECTED;
        this.value = value;
        this.callbacks.map(callback => {
          callback.onRejected(value);
        });
      }
    }

PENDING异步

执行以下代码发现并不是异步操作,应该先输出 ZX 然后是 success

let p = new ZX((resolve, reject) => {
  setTimeout(() => {
    resolve("success");
    console.log("ZX");
  });
}).then(
  value => {
    console.log(value);
  },
  reason => {
    console.log(reason);
  }
);

解决以上问题,只需要将 resolve 与 reject 执行通过 setTimeout 定义为异步任务

resolve(value) {
  if (this.status == ZX.PENDING) {
   	this.status = ZX.FULFILLED;
		this.value = value;
    setTimeout(() => {
      this.callbacks.map(callback => {
        callback.onFulfilled(value);
      });
    });
  }
}
reject(value) {
  if (this.status == ZX.PENDING) {
  	this.status = ZX.REJECTED;
    this.value = value;
    setTimeout(() => {
      this.callbacks.map(callback => {
        callback.onRejected(value);
      });
    });
  }
}

链式操作

Promise 中的 then 是链式调用执行的,所以 then 也要返回 Promise 才能实现

  1. then 的 onReject 函数是对前面 Promise 的 rejected 的处理

  2. 但该 Promise 返回状态要为 fulfilled,所以在调用 onRejected 后改变当前 promise 为 fulfilled 状态

then(onFulfilled, onRejected) {
  if (typeof onFulfilled != "function") {
    onFulfilled = value => value;
  }
  if (typeof onRejected != "function") {
    onRejected = value => value;
  }
  return new ZX((resolve, reject) => {
    if (this.status == ZX.PENDING) {
      this.callbacks.push({
        onFulfilled: value => {
          try {
            let result = onFulfilled(value);
            resolve(result);
          } catch (error) {
            reject(error);
          }
        },
        onRejected: value => {
          try {
            let result = onRejected(value);
            resolve(result);
          } catch (error) {
            reject(error);
          }
        }
      });
    }
    if (this.status == ZX.FULFILLED) {
      setTimeout(() => {
        try {
          let result = onFulfilled(this.value);
          resolve(result);
        } catch (error) {
          reject(error);
        }
      });
    }
    if (this.status == ZX.REJECTED) {
      setTimeout(() => {
        try {
          let result = onRejected(this.value);
          resolve(result);
        } catch (error) {
          reject(error);
        }
      });
    }
  });
}

下面执行测试后,链式操作已经有效了

let p = new ZX((resolve, reject) => {
  resolve("success");
  console.log("juejin.com");
})
.then(
  value => {
    console.log(value);
    return "ZX";
  },
  reason => {
    console.log(reason);
  }
)
.then(
  value => {
    console.log(value);
  },
  reason => {
    console.log(reason);
  }
);
console.log("lzx");

返回类型

如果 then 返回的是 Promise 呢?所以我们需要判断分别处理返回值为 Promise 与普通值的情况

基本实现

下面来实现不同类型不同处理机制

then(onFulfilled, onRejected) {
  if (typeof onFulfilled != "function") {
    onFulfilled = value => value;
  }
  if (typeof onRejected != "function") {
    onRejected = value => value;
  }
  return new ZX((resolve, reject) => {
    if (this.status == ZX.PENDING) {
      this.callbacks.push({
        onFulfilled: value => {
          try {
            let result = onFulfilled(value);
            if (result instanceof ZX) {
              result.then(resolve, reject);
            } else {
              resolve(result);
            }
          } catch (error) {
            reject(error);
          }
        },
        onRejected: value => {
          try {
            let result = onRejected(value);
            if (result instanceof ZX) {
              result.then(resolve, reject);
            } else {
              resolve(result);
            }
          } catch (error) {
            reject(error);
          }
        }
      });
    }
    if (this.status == ZX.FULFILLED) {
      setTimeout(() => {
        try {
          let result = onFulfilled(this.value);
          if (result instanceof ZX) {
            result.then(resolve, reject);
          } else {
            resolve(result);
          }
        } catch (error) {
          reject(error);
        }
      });
    }
    if (this.status == ZX.REJECTED) {
      setTimeout(() => {
        try {
          let result = onRejected(this.value);
          if (result instanceof ZX) {
            result.then(resolve, reject);
          } else {
            resolve(result);
          }
        } catch (error) {
          reject(error);
        }
      });
    }
  });
}

代码复用

现在发现 pendding、fulfilled、rejected 状态的代码非常相似,所以可以提取出方法Parse来复用

then(onFulfilled, onRejected) {
  if (typeof onFulfilled != "function") {
    onFulfilled = value => value;
  }
  if (typeof onRejected != "function") {
    onRejected = value => value;
  }
  return new ZX((resolve, reject) => {
    if (this.status == ZX.PENDING) {
      this.callbacks.push({
        onFulfilled: value => {
          this.parse(onFulfilled(this.value), resolve, reject);
        },
        onRejected: value => {
          this.parse(onRejected(this.value), resolve, reject);
        }
      });
    }
    if (this.status == ZX.FULFILLED) {
      setTimeout(() => {
        this.parse(onFulfilled(this.value), resolve, reject);
      });
    }
    if (this.status == ZX.REJECTED) {
      setTimeout(() => {
        this.parse(onRejected(this.value), resolve, reject);
      });
    }
  });
}
parse(result, resolve, reject) {
  try {
    if (result instanceof ZX) {
      result.then(resolve, reject);
    } else {
      resolve(result);
    }
  } catch (error) {
    reject(error);
  }
}

返回约束

then 的返回的 promise 不能是 then 相同的 Promise,下面是原生 Promise 的示例将产生错误

let promise = new Promise(resolve => {
  setTimeout(() => {
    resolve("success");
  });
});
let p = promise.then(value => {
  return p;
});

解决上面的问题来完善代码,添加当前 promise 做为 parse 的第一个参数与函数结果比对

then(onFulfilled, onRejected) {
  if (typeof onFulfilled != "function") {
    onFulfilled = value => value;
  }
  if (typeof onRejected != "function") {
    onRejected = value => value;
  }
  let promise = new ZX((resolve, reject) => {
    if (this.status == ZX.PENDING) {
      this.callbacks.push({
        onFulfilled: value => {
          this.parse(promise, onFulfilled(this.value), resolve, reject);
        },
        onRejected: value => {
          this.parse(promise, onRejected(this.value), resolve, reject);
        }
      });
    }
    if (this.status == ZX.FULFILLED) {
      setTimeout(() => {
        this.parse(promise, onFulfilled(this.value), resolve, reject);
      });
    }
    if (this.status == ZX.REJECTED) {
      setTimeout(() => {
        this.parse(promise, onRejected(this.value), resolve, reject);
      });
    }
  });
  return promise;
}
parse(promise, result, resolve, reject) {
  if (promise == result) {
    throw new TypeError("Chaining cycle detected for promise");
  }
  try {
    if (result instanceof ZX) {
      result.then(resolve, reject);
    } else {
      resolve(result);
    }
  } catch (error) {
    reject(error);
  }
}

现在进行测试也可以得到原生一样效果了

let p = new ZX((resolve, reject) => {
  resolve("success");
});
p = p.then(value => {
  return p;
});

RESOLVE

下面来实现 Promise 的 resolve 方法

static resolve(value) {
  return new ZX((resolve, reject) => {
    if (value instanceof ZX) {
      value.then(resolve, reject);
    } else {
      resolve(value);
    }
  });
}

使用普通值的测试

ZX.resolve("success").then(value => {
  console.log(value);
});

使用状态为 fulfilled 的 promise 值测试

ZX.resolve(
  new ZX(resolve => {
    resolve("success");
  })
).then(value => {
  console.log(value);
});

使用状态为 rejected 的 Promise 测试

ZX.resolve(
  new ZX((_, reject) => {
    reject("reacted");
  })
).then(
  value => {
    console.log(value);
  },
  reason => {
    console.log(reason);
  }
);

REJEDCT

下面定义 Promise 的 reject 方法

static reject(reason) {
  return new ZX((_, reject) => {
    reject(reason);
  });
}

使用测试

ZX.reject("rejected").then(null, reason => {
  console.log(reason);
});

ALL

下面来实现 Promise 的 all 方法

static all(promises) {
  let resolves = [];
  return new ZX((resolve, reject) => {
    promises.forEach((promise, index) => {
      promise.then(
        value => {
          resolves.push(value);
          if (resolves.length == promises.length) {
            resolve(resolves);
          }
        },
        reason => {
          reject(reason);
        }
      );
    });
  });
}

来对所有 Promise 状态为 fulfilled 的测试

let p1 = new ZX((resolve, reject) => {
  resolve("success-1");
});
let p2 = new ZX((resolve, reject) => {
  reject("success-2");
});
let promises = ZX.all([p1, p2]).then(
  promises => {
    console.log(promises);
  },
  reason => {
    console.log(reason);
  }
);

使用我们写的 resolve 进行测试

let p1 = ZX.resolve("success-p1");
let p2 = ZX.resolve("success-p2");
let promises = ZX.all([p1, p2]).then(
  promises => {
    console.log(promises);
  },
  reason => {
    console.log(reason);
  }
);

其中一个 Promise 为 onRejected 时的效果

let p1 = ZX.resolve("success-p1");
let p2 = ZX.reject("defail-p2");
let promises = ZX.all([p1, p2]).then(
  promises => {
    console.log(promises);
  },
  reason => {
    console.log(reason);
  }
);

RACE

下面实现 Promise 的 race 方法

static race(promises) {
  return new ZX((resolve, reject) => {
    promises.map(promise => {
      promise.then(value => {
        resolve(value);
      });
    });
  });
}

我们来进行测试

let p1 = ZX.resolve("success-p1");
let p2 = ZX.resolve("success-p2");
let promises = ZX.race([p1, p2]).then(
  promises => {
    console.log(promises);
  },
  reason => {
    console.log(reason);
  }
);

使用延迟 Promise 后的效果

let p1 = new ZX(resolve => {
  setInterval(() => {
    resolve("success-p1-2seconds");
  }, 2000);
});
let p2 = new ZX(resolve => {
  setInterval(() => {
    resolve("success-p2-1seconds");
  }, 1000);
});
let promises = ZX.race([p1, p2]).then(
  promises => {
    console.log(promises);
  },
  reason => {
    console.log(reason);
  }
);

总结:

  1. 状态改变,每次只能改变一次;
  2. then 参数不是必须的,且可以穿透执行(利用函数封装传进来的参数,无论有没有传参,通过函数形式返还);
  3. then 中的执行是异步的;
  4. 处理 pending 状态,将 then 中的执行收集后,放到 callbacks 中,当pending 状态变为 onFulfilled 或者 onRejected ,再各自的 resolve 或者 reject中执行回调;
  5. Promise 中的执行是同步的,pending 状态异步;
  6. then 链式操作,默认返还的是 onFulfilled 状态,思路是处理完上一个的返还值,返还出去新的值给后续的 then 执行,当然 then 本身是经过一层 Promise 包装的;
  7. then 中返还 promise,判断返还的是否是函数对象,如果是,在里面执行 then 并返回数值给外层的 then;
  8. 代码复用;
  9. 静态方法 resolve 和 reject;
  10. All;
  11. Race。