1. // 本来的编写方法
    2. const promise = new promise((reslove,reject)=>{})
    3. // 手写一个promise
    4. class Commitment {
    5. // 状态 PENDING FULFILLED REJECTED,三种状态分别为待定成功拒绝,并且三种方法不能逆转
    6. static PENDING = '待定'; static FULFILLED = '成功'; static REJECTED = '拒绝';
    7. constructor(func) {
    8. this.status = Commitment.PENDING //开始时进入的状态是待定状态
    9. this.result = null
    10. this.resloveCallbacks = []
    11. this.rejectCallbacks = []
    12. // 然后传入的参数函数方法,这里使用bind方法是因为类原型方法中使用了this.status,但是在函数外部并没有定义这个变量,因此要改变当前this指向
    13. try {
    14. func(this.reslove.bind(this), this.reject.bind(this))
    15. } catch (error) {
    16. this.reject(error)
    17. }
    18. }
    19. // 成功时执行的方法
    20. reslove(result) {
    21. setTimeout(() => {
    22. if (this.status === Commitment.PENDING) {
    23. this.status = Commitment.FULFILLED
    24. this.result = result
    25. this.resloveCallbacks.forEach(callback => {
    26. callback(result)
    27. })
    28. }
    29. })
    30. }
    31. // 拒绝时执行的方法
    32. reject(result) {
    33. setTimeout(() => {
    34. if (this.status === Commitment.PENDING) {
    35. this.status = Commitment.REJECTED
    36. this.result = result
    37. this.rejectCallbacks.forEach(callback => {
    38. callback(result)
    39. })
    40. }
    41. })
    42. }
    43. then(ONFILFILLED, ONREJECTED) {
    44. return new Commitment((reslove, reject) => {
    45. ONFILFILLED = typeof (ONFILFILLED) === 'function' ? ONFILFILLED : () => { }
    46. ONREJECTED = typeof (ONREJECTED) === 'function' ? ONREJECTED : () => { }
    47. if (this.status === Commitment.PENDING) {
    48. this.resloveCallbacks.push(ONFILFILLED)
    49. this.rejectCallbacks.push(ONREJECTED)
    50. }
    51. if (this.status === Commitment.FULFILLED) {
    52. setTimeout(() => {
    53. ONFILFILLED(this.result)
    54. })
    55. }
    56. if (this.status === Commitment.REJECTED) {
    57. setTimeout(() => {
    58. ONREJECTED(this.result)
    59. })
    60. }
    61. })
    62. }
    63. }
    64. console.log(1);
    65. const a = new Commitment(function (reslove, reject) {
    66. // throw new Error('抛出错误')
    67. console.log(2);
    68. setTimeout(() => {
    69. reslove(4)
    70. console.log(5);
    71. })
    72. })
    73. a.then(
    74. result => console.log(result),
    75. result => { console.log(result.message); }
    76. )
    77. console.log(3);