1. // 先定义三个常量表示状态
    2. var PENDING = 'pending';
    3. var FULFILLED = 'fulfilled';
    4. var REJECTED = 'rejected';
    5. function MyPromise(fn) {
    6. this.status = PENDING; // 初始状态为pending
    7. this.value = null; // 初始化value
    8. this.reason = null; // 初始化reason
    9. // 存一下this,以便resolve和reject里面访问
    10. var that = this;
    11. // resolve方法参数是value
    12. function resolve(value) {
    13. if(that.status === PENDING) {
    14. that.status = FULFILLED;
    15. that.value = value;
    16. }
    17. }
    18. // reject方法参数是reason
    19. function reject(reason) {
    20. if(that.status === PENDING) {
    21. that.status = REJECTED;
    22. that.reason = reason;
    23. }
    24. }
    25. try {
    26. fn(resolve, reject);
    27. } catch (error) {
    28. reject(error);
    29. }
    30. }
    31. MyPromise.prototype.then = function(onFulfilled, onRejected) {
    32. // 如果onFulfilled不是函数,给一个默认函数,返回value
    33. var realOnFulfilled = onFulfilled;
    34. if(typeof realOnFulfilled !== 'function') {
    35. realOnFulfilled = function (value) {
    36. return value;
    37. }
    38. }
    39. // 如果onRejected不是函数,给一个默认函数,返回reason的Error
    40. var realOnRejected = onRejected;
    41. if(typeof realOnRejected !== 'function') {
    42. realOnRejected = function (reason) {
    43. throw reason;
    44. }
    45. }
    46. if(this.status === FULFILLED) {
    47. onFulfilled(this.value)
    48. }
    49. if(this.status === REJECTED) {
    50. onRejected(this.reason);
    51. }
    52. }