1. class Promise {
  2. constructor(executor) {
  3. executor(this.resolve, this.reject);
  4. }
  5. // 状态
  6. status = "PENDING";
  7. // 返回的结果
  8. value = undefined;
  9. //成功的回调
  10. onfulfilled = [];
  11. //失败的回调
  12. onrejected = [];
  13. resolve = (value) => {
  14. if (this.status === "PENDING") {
  15. this.status = "FULFILLED";
  16. this.value = value;
  17. this.onfulfilled.forEach((item) => item(value));
  18. }
  19. };
  20. reject = (value) => {
  21. if (this.status === "PENDING") {
  22. this.status = "REJECTED";
  23. this.value = value;
  24. this.onrejected.forEach((item) => item(value));
  25. }
  26. };
  27. then = (onfulfilled, onrejected) => {
  28. if (this.status === "FULFILLED") {
  29. onfulfilled(this.value);
  30. } else if (this.status === "REJECTED") {
  31. onrejected(this.value);
  32. } else if (this.status === "PENDING") {
  33. this.onfulfilled.push(onfulfilled);
  34. this.onrejected.push(onrejected);
  35. }
  36. };
  37. }