# 手写 Promise

# 简易版 Promise

const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
function Promise1(executor) {
  var _this = this;
  this.state = PENDING; //状态
  this.value = undefined; //成功结果
  this.reason = undefined; //失败原因

  this.onFulfilled = []; //成功的回调
  this.onRejected = []; //失败的回调
  function resolve(value) {
    if (_this.state === PENDING) {
      _this.state = FULFILLED;
      _this.value = value;
      _this.onFulfilled.forEach((fn) => {
        console.log(fn);
        return fn(value);
      });
    }
  }
  function reject(reason) {
    if (_this.state === PENDING) {
      _this.state = REJECTED;
      _this.reason = reason;
      _this.onRejected.forEach((fn) => {
        console.log(fn);
        return fn(reason);
      });
    }
  }
  try {
    executor(resolve, reject);
  } catch (e) {
    reject(e);
  }
}
Promise1.prototype.then = function(onFulfilled, onRejected) {
  if (this.state === FULFILLED) {
    typeof onFulfilled === "function" && onFulfilled(this.value);
  }
  if (this.state === REJECTED) {
    typeof onRejected === "function" && onRejected(this.reason);
  }
  if (this.state === PENDING) {
    typeof onFulfilled === "function" && this.onFulfilled.push(onFulfilled);
    typeof onRejected === "function" && this.onRejected.push(onRejected);
  }
};
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

TODO:

  • 完成链式调用
Last Updated: 3/4/2024, 3:06:40 PM