Promise 三个状态

    1. pending
    2. fulfilled
    3. rejected

    executor 同步执行器,并为执行器定义需要的 resolve、reject

    利用 try…catch ,catch 调用 reject

    利用发布订阅设计模式解决异步代码的执行

    • this.onResolvedCallback = []; this.onRejectedCallback = [];
    • 在 then 方法中订阅
    • resolve,reject 发布

      1. class MyPromise {
      2. constructor(executor) {
      3. this.state = 'pending';
      4. this.value = undefined;
      5. this.reason = undefined;
      6. this.onResolvedCallback = [];
      7. this.onRejectedCallback = [];
      8. const resolve = (value) => {
      9. this.state = 'fulfilled';
      10. this.value = value;
      11. this.onResolvedCallback.forEach((fn) => fn());
      12. },
      13. reject = (reason) => {
      14. this.state = 'rejected';
      15. this.reason = reason;
      16. this.onRejectedCallback.forEach((fn) => fn());
      17. };
      18. try {
      19. executor(resolve, reject);
      20. } catch (reason) {
      21. reject(reason);
      22. }
      23. }
      24. then(onFulfilled, onRejected) {
      25. let x;
      26. return new MyPromise((resolve, reject) => {
      27. if (this.state === 'fulfilled') {
      28. try {
      29. x = onFulfilled(this.value);
      30. resolve();
      31. } catch (e) {
      32. reject(e);
      33. }
      34. }
      35. if (this.state === 'rejected') {
      36. try {
      37. x = onRejected(this.reason);
      38. resolve(x);
      39. } catch (e) {
      40. reject(e);
      41. }
      42. }
      43. if (this.state === 'pending') {
      44. this.onResolvedCallback.push(() => {
      45. try {
      46. x = onFulfilled(this.value);
      47. resolve(x);
      48. } catch (e) {
      49. reject(e);
      50. }
      51. });
      52. this.onRejectedCallback.push(() => {
      53. try {
      54. x = onRejected(this.reason);
      55. resolve(x);
      56. } catch (e) {
      57. reject(e);
      58. }
      59. });
      60. }
      61. });
      62. }
      63. }