# 解题思路 or 实现原理

Promise 对象是一个代理对象(代理一个值),被代理的值在Promise对象创建时可能是未知的。它允许你为异步操作的成功和失败分别绑定相应的处理方法(handlers)。 这让异步方法可以像同步方法那样返回值,但并不是立即返回最终执行结果,而是一个能代表未来出现的结果的promise对象。

promise-process.png

# Then

promise-then.png

# Promise 解决办法

promise-resolve.png

Promise Process

Promise A+

JavaScript Promise 迷你书

# 实现代码

/*
 * @Author: Rainy
 * @Date: 2019-11-14 19:25:01
 * @LastEditors: Rainy
 * @LastEditTime: 2020-03-05 09:38:05
 */

import { AnyFunction, WithParamsReturnAnyFunction, ArrayMap } from 'types';
import { isAbsType } from 'utils/type';

export interface MyPromise {}

export class MyPromise {
  readonly FULFILLED: string = 'Fulfilled';
  readonly PENDING: string = 'pending';
  readonly REJECTED: string = 'Rejected';

  state: string = this.PENDING;
  value: any = null;
  reason: any = null;
  onFulfilledCallback: ArrayMap<WithParamsReturnAnyFunction> = [];
  onRejectedCallback: ArrayMap<WithParamsReturnAnyFunction> = [];

  constructor(executor: WithParamsReturnAnyFunction) {
    this.initBind();
    try {
      executor(this.resolve, this.reject);
    } catch (error) {
      this.reject(error);
    }
  }

  initBind() {
    this.resolve = this.resolve.bind(this);
    this.reject = this.reject.bind(this);
  }

  resolve(value: any): void {
    if (this.state === this.PENDING) {
      setTimeout(() => {
        this.state = this.FULFILLED;
        this.value = value;
        this.onFulfilledCallback.forEach((cb: WithParamsReturnAnyFunction) => {
          cb && cb(this.value);
        });
      });
    }
  }

  reject(reason: any): void {
    if (this.state === this.PENDING) {
      setTimeout(() => {
        this.state = this.REJECTED;
        this.reason = reason;
        this.onRejectedCallback.forEach((cb: WithParamsReturnAnyFunction) => {
          cb && cb(this.reason);
        });
      });
    }
  }

  then(
    onFulfilled?: WithParamsReturnAnyFunction,
    onRejected?: WithParamsReturnAnyFunction
  ) {
    onFulfilled =
      typeof onFulfilled === 'function' ? onFulfilled : value => value;
    onRejected =
      typeof onRejected === 'function'
        ? onRejected
        : err => {
            throw err;
          };

    let promise2 = new MyPromise(
      (
        resolve: WithParamsReturnAnyFunction,
        reject: WithParamsReturnAnyFunction
      ) => {
        if (this.state === this.FULFILLED) {
          setTimeout(() => {
            if (onFulfilled && onRejected) {
              const x = this.tryCall(this.value, onFulfilled, onRejected);
              this.resolvePromise(promise2, x, resolve, reject);
            }
          });
        }

        if (this.state === this.REJECTED) {
          setTimeout(() => {
            if (onRejected) {
              const x = this.tryCall(this.reason, onRejected, onRejected);
              this.resolvePromise(promise2, x, resolve, reject);
            }
          });
        }

        if (this.state === this.PENDING) {
          this.onFulfilledCallback.push(value => {
            if (onFulfilled && onRejected) {
              const x = this.tryCall(value, onFulfilled, onRejected);
              this.resolvePromise(promise2, x, resolve, reject);
            }
          });

          this.onRejectedCallback.push(reason => {
            onRejected && this.tryCall(reason, onRejected, onRejected);
            if (onRejected) {
              const x = this.tryCall(reason, onRejected, onRejected);
              this.resolvePromise(promise2, x, resolve, reject);
            }
          });
        }
      }
    );
    return promise2;
  }

  private tryCall(
    value: any,
    resolve: WithParamsReturnAnyFunction,
    reject: WithParamsReturnAnyFunction
  ) {
    let x: any = null;
    try {
      x = resolve(value);
    } catch (error) {
      x = reject(error);
    }
    return x;
  }

  // Promise 解决链式调用过程
  private resolvePromise(
    promise2: MyPromise,
    x: any,
    resolve: WithParamsReturnAnyFunction,
    reject: WithParamsReturnAnyFunction
  ) {
    if (promise2 === x) {
      throw new Error('Chaining cycle detected for promise #<MyPromise>');
    }
    let called: boolean = false;
    if (x instanceof MyPromise) {
      const then = x.then;
      if (x.state === this.PENDING) {
        then.call(
          x,
          y => this.resolvePromise(promise2, y, resolve, reject),
          reason => reject(reason)
        );
      } else {
        then(resolve, reject);
      }
    } else if (isAbsType(x) === 'function' || isAbsType(x) === 'object') {
      try {
        const then = x.then;
        if (isAbsType(x) === 'function') {
          then.call(
            x,
            (y: any) => {
              if (called) {
                return;
              }
              called = true;
              this.resolvePromise(promise2, y, resolve, reject);
            },
            (reason: any) => {
              if (called) {
                return;
              }
              called = true;
              reject(reason);
            }
          );
        } else {
          resolve(x);
        }
      } catch (err) {
        if (called) {
          return;
        }
        called = true;
        reject(err);
      }
    } else {
      resolve(x);
    }
  }
}

// Method: resolve reject race all

(MyPromise as any).resolve = (value: any) => {
  return new MyPromise((resolve, reject) => {
    resolve(value);
  });
};

(MyPromise as any).reject = (value: any) => {
  return new MyPromise((resolve, reject) => {
    reject(value);
  });
};

(MyPromise as any).race = (promises: ArrayMap<MyPromise>) => {
  return new MyPromise((resolve, reject) => {
    promises.forEach((promise: any, index: number) => {
      promise.then(resolve, reject);
    });
  });
};

(MyPromise as any).all = (promises: ArrayMap<MyPromise>) => {
  let promiseArr: ArrayMap<any> = [];
  return new MyPromise((resolve, reject) => {
    promises.forEach((promise: any, index: number) => {
      promise.then((data: any) => {
        promiseArr[index] = data;
        if (index + 1 === promises.length) {
          resolve(promiseArr);
        }
      }, reject);
    });
  });
};

// prototype Method: done finally catch

(MyPromise as any).prototype.done = (
  onFulfilled: WithParamsReturnAnyFunction,
  onRejected: WithParamsReturnAnyFunction
) => {
  // @ts-ignore
  return this.then(onFulfilled, onRejected).catch(error => {
    setTimeout(() => {
      throw error;
    });
  });
};

(MyPromise as any).prototype.finally = (onFinally: AnyFunction) => {
  // @ts-ignore
  return this.then(
    (value: any) => (MyPromise as any).resolve(onFinally()).then(() => value),
    (error: any) =>
      (MyPromise as any).resolve(onFinally()).then(() => {
        throw error;
      })
  );
};

(MyPromise as any).prototype.catch = (
  onRejected: WithParamsReturnAnyFunction
) => {
  // @ts-ignore
  return this.then(void 0, onRejected);
};

// npx promises-aplus-tests index.ts -> ts 文件如何测试???
(MyPromise as any).deferred = function() {
  const dfd: any = {};
  dfd.promise = new MyPromise((resolve, reject) => {
    dfd.resolve = resolve;
    dfd.reject = reject;
  });
  return dfd;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268

# 参考

Promises/A+规范 (opens new window) -> 【翻译】Promises/A+规范 (opens new window)

Github Promise (opens new window) -> Document (opens new window)

JavaScript Promise 迷你书 (opens new window)

MDN Promise (opens new window)

手写实现满足 Promise/A+ 规范的 Promise (opens new window)

BAT 前端经典面试问题:史上最最最详细的手写 Promise 教程 (opens new window)

MDN Promise.finally (opens new window)