一、then方法中,onFulfilled方法和onRejected方法的调用会生成一个新的promise实例并返回,这两个方法返回的值会存为x
    二、保存的x需要进行判断,用于改变新promise实例的状态。

    1. const PENDING = 'pending';
    2. const FULFILLED = 'fulfilled';
    3. const REJECTED = 'rejected';
    4. function resolvePromise(promise2,x,resolve,reject){
    5. console.log(promise2,x)
    6. }
    7. class MPromise{
    8. constructor(excuter){
    9. this.status = PENDING;
    10. this.value = undefined;
    11. this.reason = undefined;
    12. this.onFulfilledCallbacks = []
    13. this.onRejectedCallbacks = []
    14. //声明resole和reject函数,这里用箭头函数可以避免this指向改变,单独方法调用,this指向window或undefined
    15. const resolve = (val) =>{
    16. if(this.status === PENDING){
    17. this.value = val
    18. this.status = FULFILLED
    19. this.onFulfilledCallbacks.forEach((fn)=> fn())
    20. }
    21. }
    22. const reject = (reason) =>{
    23. if(this.status === PENDING){
    24. this.reason = reason
    25. this.status = REJECTED
    26. this.onRejectedCallbacks.forEach((fn)=> fn())
    27. }
    28. }
    29. try{
    30. executor(resolve, reject)
    31. }catch(error){
    32. reject(error)
    33. }
    34. }
    35. //then方法核心部分是,判断promise当前status,做出不同操作
    36. //function class里面添加原型方法,不用写function关键字
    37. then(onFulfilled, onRejected){
    38. let promise2 = new Promise((resolve,reject)=>{
    39. //如果是pending状态,收集相关方法,等状态改变时再调用
    40. if(this.status === PENDING){
    41. //之前搜集回调时,没有传value和reason
    42. this.onFulfilledCallbacks.push(()=>{
    43. try{
    44. let x = onFulfilled(this.value)
    45. }catch(error){
    46. reject(error)
    47. }
    48. })
    49. this.onRejectedCallbacks.push(()=>{
    50. try{
    51. let x = onRejected(this.reason)
    52. }catch(error){
    53. reject(error)
    54. }
    55. })
    56. }
    57. if(this.status === FULFIILED){
    58. setTimeout(()=>{
    59. try{
    60. let x = onFulfilled(this.value)
    61. //这里要将新promise实例传到函数中,但是此处是在new Promise的executor中
    62. //需要将onFulfilled和onRejected写成异步方法,可以写成宏任务或者微任务,
    63. //源码中写成了微任务
    64. resolvePromise(promise2,x,resolve,reject)
    65. }catch(error){
    66. reject(error)
    67. }
    68. },0)
    69. }
    70. if(this.status === REJECTED){
    71. setTimeout(()=>{
    72. try{
    73. let x = onRjected(this.reason)
    74. resolvePromise(promise2,x,resolve,reject)
    75. }catch(error){
    76. reject(error)
    77. }
    78. },0)
    79. }
    80. })
    81. return promise2
    82. }
    83. }