手写 Promise

1. Promise/A+规范

有兴趣的同学可以去Promise/A+查看,下面只是简单的解读。

Promise 是一个对象或者函数。它有一个 then 方法。

thenable 是一个对象或者函数,用来定义 > then 方法 value 是 > Promise 状态成功时的值 reason 是 > Promise 状态失败时的值>

2. 实现一个简单的 Promise

  1. 第一步,定义 Promise 实例的初始状态
  1. function MyPromise(fn) {
  2. const that = this;
  3. that.state = 'pending'; // 初始状态
  4. that.value = null; // 调用 resolve 时的参数值
  5. that.reason = null; // 调用 reject 时的参数值
  6. }
  1. 实现 resolvereject 方法
  1. function MyPromise(fn) {
  2. ...
  3. function resolve(value) {
  4. if (that.state === 'pending') {
  5. that.value = value; // 取到 resolve 的值
  6. that.state = 'resolved' // 更改 状态
  7. }
  8. }
  9. function reject(err) {
  10. if (that.state === 'pending') {
  11. that.reason = err;
  12. that.state = 'rejected';
  13. }
  14. }
  15. }
  1. resolvereject 作为参数调用 fn
  1. function MyPromise(fn) {
  2. ...
  3. try {
  4. fn(resolve, reject)
  5. } catch(e) {
  6. reject(e)
  7. }
  8. }
  1. Promise 原型上定义 then 方法
  1. MyPromise.prototye.then = function(onFulfilled, onRejected) {
  2. let self=this;
  3. switch(self.status){
  4. case "resolved":
  5. onFullfilled(self.value);
  6. break;
  7. case "rejected":
  8. onRejected(self.reason);
  9. break;
  10. default:
  11. }
  12. }

3. 参考

  1. 实现一个完美符合Promise/A+规范的Promise