程序员成长-修炼中心 「作者:陈楚城」
导航
博客文章
  • Github (opens new window)
  • 掘金 (opens new window)
组件库 (opens new window)
关于我

chamberlain

前端持续学习者
导航
博客文章
  • Github (opens new window)
  • 掘金 (opens new window)
组件库 (opens new window)
关于我
  • 写在前面
  • vue3学习总结

  • 项目相关

  • 性能优化

  • 你不知道的css

  • 常见问题总结记录

  • 数据结构与算法

  • 设计模式

  • TS & JS进阶

  • Node

  • HTTP

  • Linux

  • 开发工具篇

  • 收藏夹

  • OS

  • Nginx

  • 项目工程化

  • 数据库

  • 计算机网络

  • 环境搭建、项目部署

  • 常用工具

  • 自动化

  • js相关

    • 函数柯里化curry
    • 继承
    • 使用setTimeout模拟setInterval
    • 手写防抖和节流
    • 手写实现拖拽
    • create
    • 手写一个call或apply
    • bind
    • 手写一个instanceOf原理
    • 手写一个JS深拷贝
    • parse和JSOn.stringify
    • 手写一个map和reduce
    • 手写一个new操作符
    • LRU缓存算法
    • 手写Promise
      • Promise 自身的状态
      • 实现 Promise
        • 1、实现一个 promise ,在 setTimeout 中去 resolve
        • 2、实现一个 promise,直接同步 resolve
        • 3、实现一个 promise,防止 resolve 多次
        • 4、实现一个 promise,可以让 then 方法链式调用
        • 5、实现一个 promise,支持空 then 函数
        • 6、实现一个 promise,支持 then 传递 thenable 对象
        • 7、实现一个 promise,支持 then 传递 promise 对象
        • 8、实现一个 promise,支持 resolve 传递 promise 对象
        • 9、实现一个 promise,处理 then 中的循环 promise
        • 10、实现一个 promise,支持静态方法 Promise.all
        • 11、实现一个 promise,支持 reject 和 catch
        • 12、实现一个 promise,支持处理完成态或失败态的then ok
    • set
    • random
    • 原型
    • 实现Symbol类型
  • QA相关

  • 文章收藏

  • note
  • jsNote
chamberlain
2022-03-14
目录

手写Promise

# 手写 Promise

Promise 对象用于表示一个异步操作的最终完成 (或失败)及其结果值

Promise A+规范 (opens new window)

# Promise 自身的状态

  1. state 存放当前的状态

  2. value 存放当前状态的值

  3. then 方法,返回值也是一个 Promise

  4. catch 方法

  5. finally 方法

  6. 静态方法,如 Promise.all、Promise.resolve

# 实现 Promise

# 1、实现一个 promise ,在 setTimeout 中去 resolve

// promise 的三种状态
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

class MyPromise {
  constructor(fn) {
    this.state = PENDING;
    this.value = undefined;
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];

    const resolve = (val) => {
      this.state = FULFILLED;
      this.value = val;
      // 执行所有的 then 方法
      this.resolvedCallbacks.map((fn) => fn());
    };
    const reject = (val) => {
      this.value = val;
      this.state = REJECTED;
      // 执行所有的 then 方法
      this.rejectedCallbacks.map((fn) => fn());
    };
    fn(resolve, reject);
  }
  then (onFulfilled) {
    let promise2 = null;
    // 处理尚未完成的promise
    if (this.state === PENDING) {
      this.resolvedCallbacks.push(onFulfilled(this.value));
      this.rejectedCallbacks.push(onRejected(this.value));
    }
  }
}
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

# 2、实现一个 promise,直接同步 resolve

// promise 的三种状态
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

class MyPromise {
  constructor(fn) {
    this.state = PENDING;
    this.value = undefined;
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];

    const resolve = (val) => {
      setTimeout(() => {
          this.state = FULFILLED;
          this.value = val;
          // 执行所有的 then 方法
          this.resolvedCallbacks.map((fn) => fn());
      });
    };
    const reject = (val) => {
      this.value = val;
      this.state = REJECTED;
      // 执行所有的 then 方法
      this.rejectedCallbacks.map((fn) => fn());
    };
    fn(resolve, reject);
  }
  then (onFulfilled) {
    let promise2 = null;
    // 处理尚未完成的promise
    if (this.state === PENDING) {
        this.resolvedCallbacks.push(onFulfilled(this.value));
        this.rejectedCallbacks.push(onRejected(this.value));
    }
  }
}
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

# 3、实现一个 promise,防止 resolve 多次

// promise 的三种状态
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

class MyPromise {
  constructor(fn) {
    this.state = PENDING;
    this.value = undefined;
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];

    const resolve = (val) => {
      setTimeout(() => {
        if (this.state === PENDING) {
          this.state = FULFILLED;
          this.value = val;
          // 执行所有的 then 方法
          this.resolvedCallbacks.map((fn) => fn());
        }
      });
    };
    const reject = (val) => {
      this.value = val;
      this.state = REJECTED;
      // 执行所有的 then 方法
      this.rejectedCallbacks.map((fn) => fn());
    };
    fn(resolve, reject);
  }
  then (onFulfilled) {
    let promise2 = null;
    // 处理尚未完成的promise
    if (this.state === PENDING) {
        this.resolvedCallbacks.push(onFulfilled(this.value));
        this.rejectedCallbacks.push(onRejected(this.value));
    }
  }
}
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

# 4、实现一个 promise,可以让 then 方法链式调用

// promise 的三种状态
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

class MyPromise {
  constructor(fn) {
    this.state = PENDING;
    this.value = undefined;
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];

    const resolve = (val) => {
      setTimeout(() => {
        if (this.state === PENDING) {
          this.state = FULFILLED;
          this.value = val;
          // 执行所有的 then 方法
          this.resolvedCallbacks.map((fn) => fn());
        }
      });
    };
    const reject = (val) => {
      this.value = val;
      this.state = REJECTED;
      // 执行所有的 then 方法
      this.rejectedCallbacks.map((fn) => fn());
    };
    fn(resolve, reject);
  }
  then (onFulfilled) {
    let promise2 = null;
    // 处理尚未完成的promise
    if (this.state === PENDING) {
      promise2 = new MyPromise((resolve, reject) => {
        this.resolvedCallbacks.push(() => {
          const x = onFulfilled(this.value);
          resolve(x)
        });
      });
    }
    return promise2;
  }
}
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

# 5、实现一个 promise,支持空 then 函数

// promise 的三种状态
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

class MyPromise {
  constructor(fn) {
    this.state = PENDING;
    this.value = undefined;
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];

    const resolve = (val) => {
      setTimeout(() => {
        if (this.state === PENDING) {
          this.state = FULFILLED;
          this.value = val;
          // 执行所有的 then 方法
          this.resolvedCallbacks.map((fn) => fn());
        }
      });
    };
    const reject = (val) => {
      this.value = val;
      this.state = REJECTED;
      // 执行所有的 then 方法
      this.rejectedCallbacks.map((fn) => fn());
    };
    fn(resolve, reject);
  }
  then (onFulfilled = (val) => val) {
    let promise2 = null;
    // 处理尚未完成的promise
    if (this.state === PENDING) {
      promise2 = new MyPromise((resolve, reject) => {
        this.resolvedCallbacks.push(() => {
          const x = onFulfilled(this.value);
          resolve(x)
        });
      });
    }
    return promise2;
  }
}
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

# 6、实现一个 promise,支持 then 传递 thenable 对象

// promise 的三种状态
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

function promiseResolutionProcedure(promise2, x, resolve, reject) {
  //   判断 thenable 对象
  if ((typeof x === "object" || typeof x === "function") && x !== null) {
    if (typeof x.then === "function") {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      resolve(x);
    }
  } else {
    resolve(x);
  }
}

class MyPromise {
  constructor(fn) {
    this.state = PENDING;
    this.value = undefined;
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];

    const resolve = (val) => {
      setTimeout(() => {
        if (this.state === PENDING) {
          this.state = FULFILLED;
          this.value = val;
          // 执行所有的 then 方法
          this.resolvedCallbacks.map((fn) => fn());
        }
      });
    };
    const reject = (val) => {
      this.value = val;
      this.state = REJECTED;
      // 执行所有的 then 方法
      this.rejectedCallbacks.map((fn) => fn());
    };
    fn(resolve, reject);
  }
  then (onFulfilled = (val) => val) {
    let promise2 = null;
    // 处理尚未完成的promise
    if (this.state === PENDING) {
      promise2 = new MyPromise((resolve, reject) => {
        this.resolvedCallbacks.push(() => {
          const x = onFulfilled(this.value);
          promiseResolutionProcedure(promise2, x, resolve, reject);
        });
      });
    }
    return promise2;
  }
}
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

# 7、实现一个 promise,支持 then 传递 promise 对象

// promise 的三种状态
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

// promise 处理过程
function promiseResolutionProcedure(promise2, x, resolve, reject) {
  //   处理 prmomise 对象
  if (x instanceof MyPromise) {
    if (x.state === PENDING) {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      x.state === FULFILLED && resolve(x.value);
      x.state === REJECTED && reject(x.value);
    }
  }

  //   判断 thenable 对象
  if ((typeof x === "object" || typeof x === "function") && x !== null) {
    if (typeof x.then === "function") {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      resolve(x);
    }
  } else {
    resolve(x);
  }
}


class MyPromise {
  constructor(fn) {
    this.state = PENDING;
    this.value = undefined;
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];

    const resolve = (val) => {
      setTimeout(() => {
        if (this.state === PENDING) {
          this.state = FULFILLED;
          this.value = val;
          // 执行所有的 then 方法
          this.resolvedCallbacks.map((fn) => fn());
        }
      });
    };
    const reject = (val) => {
      this.value = val;
      this.state = REJECTED;
      // 执行所有的 then 方法
      this.rejectedCallbacks.map((fn) => fn());
    };
    fn(resolve, reject);
  }
  then (onFulfilled = (val) => val) {
    let promise2 = null;
    // 处理尚未完成的promise
    if (this.state === PENDING) {
      promise2 = new MyPromise((resolve, reject) => {
        this.resolvedCallbacks.push(() => {
          const x = onFulfilled(this.value);
          promiseResolutionProcedure(promise2, x, resolve, reject);
        });
      });
    }
    return promise2;
  }
}
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

# 8、实现一个 promise,支持 resolve 传递 promise 对象

// promise 的三种状态
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

// promise 处理过程
function promiseResolutionProcedure(promise2, x, resolve, reject) {
  //   处理 prmomise 对象
  if (x instanceof MyPromise) {
    if (x.state === PENDING) {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      x.state === FULFILLED && resolve(x.value);
      x.state === REJECTED && reject(x.value);
    }
  }

  //   判断 thenable 对象
  if ((typeof x === "object" || typeof x === "function") && x !== null) {
    if (typeof x.then === "function") {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      resolve(x);
    }
  } else {
    resolve(x);
  }
}


class MyPromise {
  constructor(fn) {
    this.state = PENDING;
    this.value = undefined;
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];

    const resolve = (val) => {
      if ( (typeof val === "object" || typeof val === "function") && val.then) {
        promiseResolutionProcedure(this, val, resolve, reject);
        return;
      }
      setTimeout(() => {
        if (this.state === PENDING) {
          this.state = FULFILLED;
          this.value = val;
          // 执行所有的 then 方法
          this.resolvedCallbacks.map((fn) => fn());
        }
      });
    };
    const reject = (val) => {
      this.value = val;
      this.state = REJECTED;
      // 执行所有的 then 方法
      this.rejectedCallbacks.map((fn) => fn());
    };
    fn(resolve, reject);
  }
  then (onFulfilled = (val) => val) {
    let promise2 = null;
    // 处理尚未完成的promise
    if (this.state === PENDING) {
      promise2 = new MyPromise((resolve, reject) => {
        this.resolvedCallbacks.push(() => {
          const x = onFulfilled(this.value);
          promiseResolutionProcedure(promise2, x, resolve, reject);
        });
      });
    }
    return promise2;
  }
}
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

# 9、实现一个 promise,处理 then 中的循环 promise

// promise 的三种状态
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

// promise 处理过程
function promiseResolutionProcedure(promise2, x, resolve, reject) {
  if (promise2 === x) {
    throw new Error("循环引用 promise");
  }
  //   处理 prmomise 对象
  if (x instanceof MyPromise) {
    if (x.state === PENDING) {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      x.state === FULFILLED && resolve(x.value);
      x.state === REJECTED && reject(x.value);
    }
  }

  //   判断 thenable 对象
  if ((typeof x === "object" || typeof x === "function") && x !== null) {
    if (typeof x.then === "function") {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      resolve(x);
    }
  } else {
    resolve(x);
  }
}


class MyPromise {
  constructor(fn) {
    this.state = PENDING;
    this.value = undefined;
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];

    const resolve = (val) => {
      if ( (typeof val === "object" || typeof val === "function") && val.then) {
        promiseResolutionProcedure(this, val, resolve, reject);
        return;
      }
      setTimeout(() => {
        if (this.state === PENDING) {
          this.state = FULFILLED;
          this.value = val;
          // 执行所有的 then 方法
          this.resolvedCallbacks.map((fn) => fn());
        }
      });
    };
    const reject = (val) => {
      this.value = val;
      this.state = REJECTED;
      // 执行所有的 then 方法
      this.rejectedCallbacks.map((fn) => fn());
    };
    fn(resolve, reject);
  }
  then (onFulfilled = (val) => val) {
    let promise2 = null;
    // 处理尚未完成的promise
    if (this.state === PENDING) {
      promise2 = new MyPromise((resolve, reject) => {
        this.resolvedCallbacks.push(() => {
          const x = onFulfilled(this.value);
          promiseResolutionProcedure(promise2, x, resolve, reject);
        });
      });
    }
    return promise2;
  }
}
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

# 10、实现一个 promise,支持静态方法 Promise.all

// promise 的三种状态
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

// promise 处理过程
function promiseResolutionProcedure(promise2, x, resolve, reject) {
  if (promise2 === x) {
    throw new Error("循环引用 promise");
  }
  //   处理 prmomise 对象
  if (x instanceof MyPromise) {
    if (x.state === PENDING) {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      x.state === FULFILLED && resolve(x.value);
      x.state === REJECTED && reject(x.value);
    }
  }

  //   判断 thenable 对象
  if ((typeof x === "object" || typeof x === "function") && x !== null) {
    if (typeof x.then === "function") {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      resolve(x);
    }
  } else {
    resolve(x);
  }
}


class MyPromise {
  static all(promiseArray) {
    return new MyPromise((resolve, reject) => {
      const resultArray = [];
      let successTimes = 0;

      function processResult(index, data) {
        resultArray[index] = data;
        successTimes++;
        if (successTimes === promiseArray.length) {
          // 处理成功
          resolve(resultArray);
        }
      }

      for (let i = 0; i < promiseArray.length; i++) {
        promiseArray[i].then(
          (data) => {
            processResult(i, data);
          },
          (err) => {
            // 处理失败
            reject(err);
          }
        );
      }
    });
  }
  constructor(fn) {
    this.state = PENDING;
    this.value = undefined;
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];

    const resolve = (val) => {
      if ( (typeof val === "object" || typeof val === "function") && val.then) {
        promiseResolutionProcedure(this, val, resolve, reject);
        return;
      }
      setTimeout(() => {
        if (this.state === PENDING) {
          this.state = FULFILLED;
          this.value = val;
          // 执行所有的 then 方法
          this.resolvedCallbacks.map((fn) => fn());
        }
      });
    };
    const reject = (val) => {
      this.value = val;
      this.state = REJECTED;
      // 执行所有的 then 方法
      this.rejectedCallbacks.map((fn) => fn());
    };
    fn(resolve, reject);
  }
  then (onFulfilled = (val) => val) {
    let promise2 = null;
    // 处理尚未完成的promise
    if (this.state === PENDING) {
      promise2 = new MyPromise((resolve, reject) => {
        this.resolvedCallbacks.push(() => {
          const x = onFulfilled(this.value);
          promiseResolutionProcedure(promise2, x, resolve, reject);
        });
      });
    }
    return promise2;
  }
}
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

# 11、实现一个 promise,支持 reject 和 catch

// promise 的三种状态
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

//   promise 处理过程
function promiseResolutionProcedure(promise2, x, resolve, reject) {
  if (promise2 === x) {
    throw new Error("循环引用 promise");
  }
  //   处理 prmomise 对象
  if (x instanceof MyPromise) {
    if (x.state === PENDING) {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      x.state === FULFILLED && resolve(x.value);
      x.state === REJECTED && reject(x.value);
    }
  }

  //   判断 thenable 对象
  if ((typeof x === "object" || typeof x === "function") && x !== null) {
    if (typeof x.then === "function") {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      resolve(x);
    }
  } else {
    resolve(x);
  }
}

class MyPromise {
  static all(promiseArray) {
    return new MyPromise((resolve, reject) => {
      const resultArray = [];
      let successTimes = 0;

      function processResult(index, data) {
        resultArray[index] = data;
        successTimes++;
        if (successTimes === promiseArray.length) {
          // 处理成功
          resolve(resultArray);
        }
      }

      for (let i = 0; i < promiseArray.length; i++) {
        promiseArray[i].then(
          (data) => {
            processResult(i, data);
          },
          (err) => {
            // 处理失败
            reject(err);
          }
        );
      }
    });
  }
  constructor(fn) {
    this.state = PENDING;
    this.value = undefined;
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];

    const resolve = (val) => {
      if (
        (typeof val === "object" || typeof val === "function") &&
        val.then
      ) {
        promiseResolutionProcedure(this, val, resolve, reject);
        return;
      }
      setTimeout(() => {
        if (this.state === PENDING) {
          this.state = FULFILLED;
          this.value = val;
          // 执行所有的 then 方法
          this.resolvedCallbacks.map((fn) => fn());
        }
      });
    };
    const reject = (val) => {
      if (
        (typeof val === "object" || typeof val === "function") &&
        val.then
      ) {
        promiseResolutionProcedure(this, val, resolve, reject);
        return;
      }
      setTimeout(() => {
        if (this.state === PENDING) {
          this.value = val;
          this.state = REJECTED;
          // 执行所有的 then 方法
          this.rejectedCallbacks.map((fn) => fn());
        }
      });
    };
    fn(resolve, reject);
  }

  then(
  onFulfilled = (val) => val,
   onRejected = (err) => {
    throw new Error(err);
  }
  ) {
    let promise2 = null;
    // 处理尚未完成的promise
    if (this.state === PENDING) {
      promise2 = new MyPromise((resolve, reject) => {
        this.resolvedCallbacks.push(() => {
          const x = onFulfilled(this.value);
          promiseResolutionProcedure(promise2, x, resolve, reject);
        });

        this.rejectedCallbacks.push(() => {
          const x = onRejected(this.value);
          promiseResolutionProcedure(promise2, x, resolve, reject);
        });
      });
    }
    return promise2;
  }
}
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

# 12、实现一个 promise,支持处理完成态或失败态的then ok

// promise 的三种状态
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

//   promise 处理过程
function promiseResolutionProcedure(promise2, x, resolve, reject) {
  if (promise2 === x) {
    throw new Error("循环引用 promise");
  }
  //   处理 prmomise 对象
  if (x instanceof MyPromise) {
    if (x.state === PENDING) {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      x.state === FULFILLED && resolve(x.value);
      x.state === REJECTED && reject(x.value);
    }
  }

  //   判断 thenable 对象
  if ((typeof x === "object" || typeof x === "function") && x !== null) {
    if (typeof x.then === "function") {
      x.then((y) => {
        promiseResolutionProcedure(promise2, y, resolve, reject);
      }, reject);
    } else {
      resolve(x);
    }
  } else {
    resolve(x);
  }
}

class MyPromise {
  static all(promiseArray) {
    return new MyPromise((resolve, reject) => {
      const resultArray = [];
      let successTimes = 0;

      function processResult(index, data) {
        resultArray[index] = data;
        successTimes++;
        if (successTimes === promiseArray.length) {
          // 处理成功
          resolve(resultArray);
        }
      }

      for (let i = 0; i < promiseArray.length; i++) {
        promiseArray[i].then(
          (data) => {
            processResult(i, data);
          },
          (err) => {
            // 处理失败
            reject(err);
          }
        );
      }
    });
  }
  constructor(fn) {
    this.state = PENDING;
    this.value = undefined;
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];

    const resolve = (val) => {
      if (
        (typeof val === "object" || typeof val === "function") &&
        val.then
      ) {
        promiseResolutionProcedure(this, val, resolve, reject);
        return;
      }
      setTimeout(() => {
        if (this.state === PENDING) {
          this.state = FULFILLED;
          this.value = val;
          // 执行所有的 then 方法
          this.resolvedCallbacks.map((fn) => fn());
        }
      });
    };
    const reject = (val) => {
      if (
        (typeof val === "object" || typeof val === "function") &&
        val.then
      ) {
        promiseResolutionProcedure(this, val, resolve, reject);
        return;
      }
      setTimeout(() => {
        if (this.state === PENDING) {
          this.value = val;
          this.state = REJECTED;
          // 执行所有的 then 方法
          this.rejectedCallbacks.map((fn) => fn());
        }
      });
    };
    fn(resolve, reject);
  }

  then(
  onFulfilled = (val) => val,
   onRejected = (err) => {
    throw new Error(err);
  }
  ) {
    let promise2 = null;
    // 处理已经完成的promise
    if (this.state === FULFILLED) {
      promise2 = new MyPromise((resolve, reject) => {
        const x = onFulfilled(this.value);
        promiseResolutionProcedure(promise2, x, resolve, reject);
      });
    }

    // 处理已经完成的promise
    if (this.state === REJECTED) {
      promise2 = new MyPromise((resolve, reject) => {
        const x = onRejected(this.value);
        promiseResolutionProcedure(promise2, x, resolve, reject);
      });
    }

    // 处理尚未完成的promise
    if (this.state === PENDING) {
      promise2 = new MyPromise((resolve, reject) => {
        this.resolvedCallbacks.push(() => {
          const x = onFulfilled(this.value);
          promiseResolutionProcedure(promise2, x, resolve, reject);
        });

        this.rejectedCallbacks.push(() => {
          const x = onRejected(this.value);
          promiseResolutionProcedure(promise2, x, resolve, reject);
        });
      });
    }
    return promise2;
  }
}
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
更新时间: 3/15/2022, 12:28:01 AM
LRU缓存算法
set

← LRU缓存算法 set→

最近更新
01
02
网站
06-10
03
nav
06-09
更多文章>
Theme by Vdoing | Copyright © 2019-2022 chamberlain | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式