1. function Promise2(fn) {
    2. let self = this;
    3. self.PromiseValue = undefined;
    4. self.status = "pending";
    5. self.onResolvedCallbacks = [];
    6. self.onRejectedCallbacks = [];
    7. const resolve = (value) => {
    8. if (self.status === "pending") {
    9. self.status = "fulfilled";
    10. self.PromiseValue = value;
    11. self.onResolvedCallbacks.forEach((fn) => fn());
    12. }
    13. };
    14. const reject = (reason) => {
    15. if (self.status === "pending") {
    16. self.status = "rejected";
    17. self.PromiseValue = reason;
    18. self.onRejectedCallbacks.forEach((fn) => fn());
    19. }
    20. };
    21. try {
    22. fn(resolve, reject);
    23. } catch (error) {
    24. reject(error);
    25. }
    26. }
    27. Promise2.prototype.then = function(onFulfilled, onRejected) {
    28. if (this.status === "pending") {
    29. this.onResolvedCallbacks.push(() => {
    30. this.PromiseValue = onFulfilled(this.PromiseValue);
    31. });
    32. this.onRejectedCallbacks.push(() => {
    33. this.PromiseValue = onRejected(this.PromiseValue);
    34. });
    35. }
    36. if (this.status === "fulfilled") {
    37. try {
    38. this.PromiseValue = onFulfilled(this.PromiseValue);
    39. } catch (error) {
    40. this.PromiseValue = error;
    41. this.status = "rejected";
    42. }
    43. } else if (this.status === "rejected") {
    44. try {
    45. this.PromiseValue = onRejected(this.PromiseValue);
    46. this.status = "fulfilled";
    47. } catch (error) {
    48. this.PromiseValue = error;
    49. }
    50. }
    51. return this;
    52. };
    53. new Promise2((resolve, reject) => {
    54. console.log("执行同步");
    55. resolve(10);
    56. })
    57. .then((value) => {
    58. console.log("正在执行then");
    59. console.log(value);
    60. let n = value + 1;
    61. return n;
    62. })
    63. .then((value) => {
    64. console.log("执行第二个then");
    65. console.log(value);
    66. });