🔥🔥🔥手写实现Promise

手写Promise相关经常是各大公司手撕代码环节会被问到的问题,本文手把手带你实现一遍Promise的核心功能和方法。

基础功能实现

js 复制代码
    const test = new Promise((reslove, reject) => {
      reslove("siu");
    });
    test.then((res) => {
      console.log(res); // siu
    });

接下来实现这一部分功能

js 复制代码
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
class selfPromise {
  constructor(exec) {
    this.status = PENDING;
    this.result = null;
    // 用bind绑定this或resolve和reject用箭头函数 让它绑定到实例
    exec(this.resolve.bind(this), this.reject.bind(this));
  }
  resolve(result) {
    // 只有在PENDING状态下,才需要改变状态和记录结果
    // 这样也保证了Promise状态一旦改变就不能再改变
    // reject和reslove相同
    if (this.status === PENDING) {
      this.status = FULFILLED;
      this.result = result;
    }
  }
  reject(reason) {
    if (this.status === PENDING) {
      this.status = REJECTED;
      this.result = reason;
    }
  }
  then(onFULFILLED, onREJECTED) {
    if (this.status === FULFILLED) {
      onFULFILLED(this.result);
    }
    if (this.status === REJECTED) {
      onREJECTED(this.result);
    }
  }
}
const test = new selfPromise((resolve, reject) => {
  resolve("siu is good");
  //   reject("reject is good");
});
test.then(
  (res) => {
    console.log(res); // siu is good
  },
  (rej) => {
    console.log(rej); //reject is good
  }
);

实现异步逻辑和抛出错误

js 复制代码
const test = new selfPromise((resolve, reject) => {
  setTimeout(() => {
    resolve("siu is good");
  });
  //   throw new Error("error");
});
test.then(
  (res) => {
    console.log(res); // 无输出
  },
  (rej) => {
    console.log(rej);
  }
);

因为setTimeout方法执行将resolve函数导致then方法比resolve先执行,所以当时Promise状态为pending,在then中还没有处理pending的情况,导致无输出。

处理执行函数时如果抛出错误 这时Promise的状态因由pending转为rejected,而捕获异常需要用到try catch

js 复制代码
  constructor(exec) {
    this.status = PROMISE_PENDING_STATE;
    this.result = null;
    this.reason = null;
    this.resolveCallbacks = [];
    this.rejectCallbacks = [];
    try {
      exec(this.resolve.bind(this), this.reject.bind(this));
    } catch (error) {
      this.reject(error);
    }
  }
    resolve(result) {
    if (this.status === PENDING) {
      this.status = FULFILLED;
      this.result = result;
      this.resolveCallbacks.forEach((fn) => {
        fn(result);
      });
    }
  }
  reject(reason) {
    if (this.status === PENDING) {
      this.status = REJECTED;
      this.reason = reason;
      this.rejectCallbacks.forEach((fn) => {
        fn(reason);
      });
    }
  }
  then(onFULFILLED, onREJECTED) {
    if (this.status === PENDING) {
      this.resolveCallbacks.push(onFULFILLED);
      this.rejectCallbacks.push(onREJECTED);
    }
    if (this.status === FULFILLED) {
      onFULFILLED(this.result);
    }
    if (this.status === REJECTED) {
      onREJECTED(this.reason);
    }
  }
}
const test = new selfPromise((resolve, reject) => {
  setTimeout(() => {
    resolve("siu is good");
  });
  //   throw new Error("error");
});
test.then(
  (res) => {
    console.log(res); // siu is good
  },
  (rej) => {
    console.log(rej); //reject is good
  }
);

继续优化then功能

  1. 处理then函数参数
js 复制代码
  then(onFULFILLED, onREJECTED) {
    // Promise 中的 then 方法回调参数都是可选的,当调用 then 方法未传参数时,需要给默认值
        onFULFILLED =
      typeof onFULFILLED === "function"
        ? onFULFILLED
        // 值穿透
        : (value) => {
            return value;
          };
    onREJECTED =
      typeof onREJECTED === "function"
        ? onREJECTED
        : (reason) => {
            throw reason;
          };
    ...
    }
    
  1. Promisethen方法是异步执行的。让then方法在同步任务完成后执行,通过setTimeout方法将then方法的执行延后,在同步任务执行完毕后then方法才会被调用。
js 复制代码
  resolve(result) {
    setTimeout(() => {
      if (this.status === PENDING) {
        this.status = FULFILLED;
        this.result = result;
        this.resolveCallbacks.forEach((fn) => {
          fn(result);
        });
      }
    });
  }
  reject(reason) {
    setTimeout(() => {
      if (this.status === PENDING) {
        this.status = REJECTED;
        this.reason = reason;
        this.rejectCallbacks.forEach((fn) => {
          fn(reason);
        });
      }
    });
  }
  then(onFULFILLED, onREJECTED) {
    if (this.status === PENDING) {
      this.resolveCallbacks.push(onFULFILLED);
      this.rejectCallbacks.push(onREJECTED);
    }
    if (this.status === FULFILLED) {
      setTimeout(() => {
        onFULFILLED(this.result);
      });
    }
    if (this.status === REJECTED) {
      setTimeout(() => {
        onREJECTED(this.reason);
      });
    }
  }
}
console.log("1");
const test = new selfPromise((resolve, reject) => {
  resolve("siu is good");
});
test.then(
  (res) => {
    console.log("3  " + res);
  },
  (rej) => {}k
);
console.log("2");
//输出
//1 
//2
//3 siu is good
  1. 链式调用 then方法的链式调用 要实现链式调用需要让then方法有返回值并且是Promise对象 下一个then方法会依赖上一个then方法的回调函数返回值
js 复制代码
  then(onFULFILLED, onREJECTED) {
  ...
      //重复逻辑太多抽离成函数
      const fn = (fn) => {
        try {
          const result = fn(this.result);
          if (result instanceof selfPromise) {
            result.then(
              (res) => {
                resolve(res);
                // console.log(res);
              },
              (err) => {
                reject(err);
              }
            );
          } else {
            resolve(result);
          }
        } catch (err) {
          reject(err);
        }
      };
      if (this.status === FULFILLED) {
        setTimeout(() => {
          //   try {
          //     const result = onFULFILLED(this.result);
          //     resolvePromise(newPromise, result, resolve, reject);
          //   } catch (error) {
          //     reject(error);
          //   }
          fn(onFULFILLED);
        });
      }
      if (this.status === REJECTED) {
        setTimeout(() => {
          //   try {
          //     const reason = onREJECTED(this.result);
          //     resolvePromise(newPromise, reason, resolve, reject);
          //   } catch (error) {
          //     reject(error);
          //   }
          fn(onREJECTED);
        });
      }
      if (this.status === PENDING) {
        this.resolveCallbacks.push(() => {
          //   try {
          //     const result = onFULFILLED(this.result);
          //     resolvePromise(newPromise, result, resolve, reject);
          //   } catch (error) {
          //     reject(error);
          //   }
          fn(onFULFILLED);
        });
        this.rejectCallbacks.push(() => {
          //   try {
          //     const result = onREJECTED(this.result);
          //     resolvePromise(newPromise, result, resolve, reject);
          //   } catch (error) {
          //     reject(error);
          //   }
          fn(onREJECTED);
        });
      }
    });
    return newPromise;
    }
    const test = new selfPromise((resolve, reject) => {
  resolve("siu is good");
});
test
  .then((res) => {
    console.log("1   " + res);
    return new selfPromise((resolve, reject) => {
      resolve(res);
    });
  })
  .then((res) => {
    console.log(res);
  });
// 1 siu is good
// siu is good

Promise 实例对象方法的实现

catch

catch(onRejected):该方法是 then() 方法的一个特殊形式,用于注册对 Promise 拒绝状态的处理函数。它只接收一个参数 onRejected,表示在 Promise 拒绝时要执行的回调函数。catch() 方法也返回一个新的 Promise 对象,可以用于链式调用。

typescript 复制代码
catch(onREJECTED) {
    return this.then(null, onREJECTED);
 }
 const test = new selfPromise((resolve, reject) => {
  reject("siu siu siu");
});
test.then().catch((rea) => {
  console.log(rea);
});
// siu siu siu

finally

finally(onFinally):该方法在 Promise 的状态最终确定后执行指定的回调函数,无论是解决还是拒绝状态。它接收一个参数 onFinally,表示要执行的回调函数。finally() 方法返回一个新的 Promise 对象,可以用于链式调用。

js 复制代码
  finally(onFinally) {
    return this.then(
      (value) => selfPromise.resolve(onFinally()).then(() => value),
      (reason) =>
        selfPromise.resolve(onFinally()).then(() => {
          throw reason;
        })
    );
  }
  const test = new selfPromise((resolve, reject) => {
  reject("siu siu siu");
  //resolve("666");
});
test
  .then()
  .catch((rea) => {
    console.log(rea);
  })
  .finally(() => {
    console.log("123");
  });
  //siu siu siu
  //123

Promise 静态方法的实现

⭐⭐⭐ all:该方法接收一个可迭代对象(比如数组)作为参数,返回一个新的 Promise 对象。这个新的 Promise 对象在所有传入的 Promise 都解决时才会解决,并把所有解决结果按顺序作为数组传递给回调函数。如果传入的 Promise 中有任何一个被拒绝,它将立即拒绝并把第一个拒绝原因传递给回调函数

js 复制代码
  static all(promises) {
    let result = [];
    let resolveCount = 0;
    return new selfPromise((resolve, reject) => {
      for (let i = 0; i < promises.length; i++) {
        promises[i].then(
          (res) => {
            // 记录数据
            result[i] = res;
            resolveCount++;
            if (resolveCount === promises.length) {
              resolve(result);
            }
          },
          (reason) => {
            reject(reason);
          }
        );
      }
    });
  }
const t1 = Promise.resolve("1");
const t2 = Promise.resolve("2");
const t3 = Promise.resolve("3");
const t = selfPromise.all([t1, t2, t3]).then((res) => {
  console.log(res);
});

any:Promise.any(iterable)该方法接收一个可迭代对象(比如数组)作为参数,返回一个新的 Promise 对象。这个新的 Promise 对象在传入的任意一个 Promise 解决时立即解决,并将该解决值传递给回调函数。如果传入的所有 Promise 都被拒绝,它将立即拒绝并把所有拒绝原因作为数组传递给回调函数。

js 复制代码
  static any(promises) {
    return new selfPromise((resolve, reject) => {
      const errors = [];
      let completedCount = 0;
      for (let i = 0; i < promises.length; i++) {
        promises[i].then(
          (res) => {
            resolve(res);
          },
          (err) => {
            errors.push({ index: i, err});
            completedCount++;
            if (completedCount === promises.length) {
              reject(new AggregateError(errors));
            }
          }
        );
      }
   });
  }

race(iterable):该方法接收一个可迭代对象(比如数组)作为参数,返回一个新的 Promise 对象。这个新的 Promise 对象在传入的任意一个 Promise 解决或拒绝时立即解决或拒绝,并把第一个解决或拒绝的结果传递给回调函数。

js 复制代码
  static race(promises) {
    return new selfPromise((resolve, reject) => {
      for (let i = 0; i < promises.length; i++) {
        promises[i].then(
          (res) => {
            resolve(res);
          },
          (reason) => {
            reject(reason);
          }
        );
      }
    });
  }
const t1 = Promise.resolve("1");
const t2 = Promise.resolve("2");
const t3 = Promise.resolve("3");
const t4 = Promise.reject("4");
selfPromise.race([t2, t1, t3, t4]).then((res) => {
  console.log(res);
});
// 2

allSettled:该方法接收一个可迭代对象(比如数组)作为参数,返回一个新的 Promise 对象。这个新的 Promise 对象在传入的所有 Promise 都已解决或拒绝时才会解决,并把所有 Promise 的最终结果作为对象数组传递给回调函数。每个对象包含一个 status 属性,表示 Promise 的状态("fulfilled" 表示解决,"rejected" 表示拒绝),以及一个 valuereason 属性,分别表示解决值或拒绝原因。

js 复制代码
  static allSettled(promises) {
    return new selfPromise((resolve) => {
      const results = [];
      let pendingCount = promises.length;
      for (let i = 0; i < promises.length; i++) {
        promises[i]
          .then(
            (value) => {
              results[i] = { status: "fulfilled", value };
            },
            (reason) => {
              results[i] = { status: "rejected", reason };
            }
          )
          .finally(() => {
            pendingCount--;
            if (pendingCount === 0) {
              resolve(results);
            }
          });
      }
    });
  }
const t1 = Promise.resolve("1");
const t2 = Promise.resolve("2");
const t3 = Promise.resolve("3");
const t4 = Promise.reject("4");
selfPromise.allSettled([t1, t2, t3, t4]).then((res) => {
  console.log(res);
});
// [
//     { status: 'fulfilled', value: '1' },
//     { status: 'fulfilled', value: '2' },
//     { status: 'fulfilled', value: '3' },
//     { status: 'rejected', reason: '4' }
//   ]

最后的完整代码

ini 复制代码
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
class selfPromise {
  constructor(exec) {
    this.status = PENDING;
    this.result = null;
    this.resolveCallbacks = [];
    this.rejectCallbacks = [];
    exec(this.resolve.bind(this), this.reject.bind(this));
  }
  resolve(result) {
    setTimeout(() => {
      if (this.status === PENDING) {
        this.status = FULFILLED;
        this.result = result;
        this.resolveCallbacks.forEach((fn) => {
          fn(result);
        });
      }
    });
  }
  reject(result) {
    setTimeout(() => {
      if (this.status === PENDING) {
        this.status = REJECTED;
        this.result = result;
        this.rejectCallbacks.forEach((fn) => {
          fn(result);
        });
      }
    });
  }
  then(onFULFILLED, onREJECTED) {
    // Promise 中的 then 方法回调参数都是可选的,当调用 then 方法未传参数时,需要给默认值
    onFULFILLED =
      typeof onFULFILLED === "function"
        ? onFULFILLED
        : (value) => {
            return value;
          };
    onREJECTED =
      typeof onREJECTED === "function"
        ? onREJECTED
        : (reason) => {
            throw reason;
          };
    const newPromise = new selfPromise((resolve, reject) => {
      const fn = (fn) => {
        try {
          const result = fn(this.result);
          if (result instanceof selfPromise) {
            result.then(
              (res) => {
                resolve(res);
              },
              (err) => {
                reject(err);
              }
            );
          } else {
            resolve(result);
          }
        } catch (err) {
          reject(err);
        }
      };
      if (this.status === FULFILLED) {
        setTimeout(() => {
          fn(onFULFILLED);
        });
      }
      if (this.status === REJECTED) {
        setTimeout(() => {
          fn(onREJECTED);
        });
      }
      if (this.status === PENDING) {
        this.resolveCallbacks.push(() => {
          fn(onFULFILLED);
        });
        this.rejectCallbacks.push(() => {
          fn(onREJECTED);
        });
      }
    });
    return newPromise;
  }
  catch(onREJECTED) {
    return this.then(null, onREJECTED);
  }
  finally(onFinally) {
    return this.then(
      (value) => selfPromise.resolve(onFinally()).then(() => value),
      (reason) =>
        selfPromise.resolve(onFinally()).then(() => {
          throw reason;
        })
    );
  }
  static resolve(result) {
    return new selfPromise((resolve, reject) => {
      if (result instanceof selfPromise) {
        result.then(
          (res) => {
            resolve(res);
          },
          (err) => {
            reject(err);
          }
        );
      } else {
        resolve(result);
      }
    });
  }

  static reject(result) {
    return new selfPromise((resolve, reject) => {
      reject(result);
    });
  }
  static all(promises) {
    let result = [];
    let resolveCount = 0;
    return new selfPromise((resolve, reject) => {
      for (let i = 0; i < promises.length; i++) {
        promises[i].then(
          (res) => {
            // 记录数据
            result[i] = res;
            resolveCount++;
            if (resolveCount === promises.length) {
              resolve(result);
            }
          },
          (reason) => {
            reject(reason);
          }
        );
      }
    });
  }
  static any(promises) {
    return new selfPromise((resolve, reject) => {
      const errors = [];
      let completedCount = 0;
      for (let i = 0; i < promises.length; i++) {
        promises[i].then(
          (res) => {
            resolve(res);
          },
          (err) => {
            errors.push({ index: i, err });
            completedCount++;
            if (completedCount === promises.length) {
              reject(new AggregateError(errors));
            }
          }
        );
      }
    });
  }
  static race(promises) {
    return new selfPromise((resolve, reject) => {
      for (let i = 0; i < promises.length; i++) {
        promises[i].then(
          (res) => {
            resolve(res);
          },
          (reason) => {
            reject(reason);
          }
        );
      }
    });
  }
  static allSettled(promises) {
    return new selfPromise((resolve) => {
      const results = [];
      let pendingCount = promises.length;
      for (let i = 0; i < promises.length; i++) {
        promises[i]
          .then(
            (value) => {
              results[i] = { status: FULFILLED, value };
            },
            (reason) => {
              results[i] = { status: REJECTED, reason };
            }
          )
          .finally(() => {
            pendingCount--;
            if (pendingCount === 0) {
              resolve(results);
            }
          });
      }
    });
  }
}

总结

代码可优化的东西很多,更多作为自我学习,也希望对你有所帮助。

相关推荐
栈老师不回家42 分钟前
Vue 计算属性和监听器
前端·javascript·vue.js
前端啊龙1 小时前
用vue3封装丶高仿element-plus里面的日期联级选择器,日期选择器
前端·javascript·vue.js
一颗松鼠1 小时前
JavaScript 闭包是什么?简单到看完就理解!
开发语言·前端·javascript·ecmascript
小远yyds1 小时前
前端Web用户 token 持久化
开发语言·前端·javascript·vue.js
阿伟来咯~2 小时前
记录学习react的一些内容
javascript·学习·react.js
吕彬-前端2 小时前
使用vite+react+ts+Ant Design开发后台管理项目(五)
前端·javascript·react.js
学前端的小朱2 小时前
Redux的简介及其在React中的应用
前端·javascript·react.js·redux·store
guai_guai_guai2 小时前
uniapp
前端·javascript·vue.js·uni-app
也无晴也无风雨2 小时前
在JS中, 0 == [0] 吗
开发语言·javascript
帅比九日3 小时前
【HarmonyOS Next】封装一个网络请求模块
前端·harmonyos