1. 初始结构
    2. this指向
    3. 执行异常
    4. 异步
    5. 回调保存
    1. console.log("promise");
    2. class myPromise {
    3. static PENDING = "待定";
    4. static FULFILLED = "成功";
    5. static REJECTED = "拒绝";
    6. constructor(func) {
    7. this.status = myPromise.PENDING
    8. this.result = null
    9. this.resolveCallbacks = [] // 待定状态下保存回调函数
    10. this.rejectCallbacks = []
    11. try {
    12. // 修改this指向
    13. func(this.resolve.bind(this), this.reject.bind(this))
    14. } catch (err) {
    15. // 执行异常处理
    16. console.log(err);
    17. this.reject(err)
    18. }
    19. }
    20. resolve(result) {
    21. // 延时函数模拟异步,执行处理后的回调
    22. setTimeout(() => {
    23. if (this.status === myPromise.PENDING) {
    24. this.status = myPromise.FULFILLED
    25. this.result = result
    26. this.resolveCallbacks.forEach(cb => {
    27. cb(result)
    28. })
    29. }
    30. })
    31. }
    32. reject(result) {
    33. setTimeout(() => {
    34. if (this.status === myPromise.PENDING) {
    35. this.status = myPromise.REJECTED
    36. this.result = result
    37. this.rejectCallbacks.forEach(cb => {
    38. cb(result)
    39. })
    40. }
    41. })
    42. }
    43. // then方法
    44. then(onFULFILED, onREJECTED) {
    45. return new myPromise((resolve, reject) => {
    46. onFULFILED = typeof onFULFILED === 'function' ? onFULFILED : () => { }
    47. onREJECTED = typeof onREJECTED === 'function' ? onFULFILED : () => { }
    48. if (this.status === myPromise.PENDING) {
    49. // 待定状态下,回调保存
    50. this.resolveCallbacks.push(onFULFILED)
    51. this.rejectCallbacks.push(onREJECTED)
    52. }
    53. if (this.status === myPromise.FULFILLED) {
    54. // 模拟异步处理
    55. setTimeout(() => {
    56. onFULFILED(this.result)
    57. })
    58. }
    59. if (this.status === myPromise.REJECTED) {
    60. setTimeout(() => {
    61. onREJECTED(this.result)
    62. })
    63. }
    64. })
    65. }
    66. }
    67. console.log("1");
    68. var p = new myPromise((resolve, reject) => {
    69. console.log("2");
    70. setTimeout(() => {
    71. // console.log(p.status);
    72. resolve("test")
    73. reject("test-reject")
    74. // console.log(p.status);
    75. console.log("4");
    76. })
    77. // throw new Error("出错了")
    78. })
    79. p.then(
    80. res => {
    81. console.log("then-status", p.status);
    82. console.log(res);
    83. },
    84. res => { console.log(res.message); }
    85. ).then(
    86. res => { console.log("2-then", res); },
    87. res => { console.log(res.message); }
    88. )
    89. console.log("3");