一、Executor中异步操作的处理
    executor中异步操作,then方法中callbacks需要在promise.status改变后再执行
    二、then方法的多次调用
    多次调用then方法,callbacks会按照顺序来执行。
    此处用到了发布订阅模式,收集then方法中回调时用到了订阅,resolve和reject方法执行时用到了发布。

    1. const PENDING = 'pending';
    2. const FULFILLED = 'fulfilled';
    3. const REJECTED = 'rejected';
    4. class MPromise{
    5. constructor(excuter){
    6. this.status = PENDING;
    7. this.value = undefined;
    8. this.reason = undefined;
    9. this.onFulfilledCallbacks = []
    10. this.onRejectedCallbacks = []
    11. //声明resole和reject函数,这里用箭头函数可以避免this指向改变,单独方法调用,this指向window或undefined
    12. const resolve = (val) =>{
    13. if(this.status === PENDING){
    14. this.value = val
    15. this.status = FULFILLED
    16. this.onFulfilledCallbacks.forEach((fn)=> fn())
    17. }
    18. }
    19. const reject = (reason) =>{
    20. if(this.status === PENDING){
    21. this.reason = reason
    22. this.status = REJECTED
    23. this.onRejectedCallbacks.forEach((fn)=> fn())
    24. }
    25. }
    26. try{
    27. executor(resolve, reject)
    28. }catch(error){
    29. reject(error)
    30. }
    31. }
    32. //then方法核心部分是,判断promise当前status,做出不同操作
    33. //function class里面添加原型方法,不用写function关键字
    34. then(onFulfilled, onRejected){
    35. //如果是pending状态,收集相关方法,等状态改变时再调用
    36. if(this.status === PENDING){
    37. //之前搜集回调时,没有传value和reason
    38. this.onFulfilledCallbacks.push(()=>{
    39. onFulfilled(this.value)
    40. })
    41. this.onRejectedCallbacks.push(()=>{
    42. onRejected(this.reason)
    43. })
    44. }
    45. if(this.status === FULFIILED){
    46. onFulfilled(this.value)
    47. }
    48. if(this.status === REJECTED){
    49. onRjected(this.reason)
    50. }
    51. }
    52. }