手写Promise

  1. class MyPromise {
  2. constructor(excutorCallBack) {
  3. this.status = "pending";
  4. this.value = undefined;
  5. this.resolveCallbackArr = [];
  6. this.rejectCallbackArr = [];
  7. const resolveFn = (result) => {
  8. // 这里加setTimeout延时,主要是为了让then里面的回调先被添加到对应的数组中,之后有回调可以循环执行
  9. setTimeout(() => {
  10. if (this.status === "pending") {
  11. this.status = "resolved";
  12. this.value = result;
  13. if (this.resolveCallbackArr.length) this.resolveCallbackArr.forEach(item => item(this.value));
  14. };
  15. }, 0)
  16. }
  17. const rejectFn = (reason) => {
  18. // 这里加setTimeout延时,主要是为了让then里面的回调先被添加到对应的数组中,之后有回调可以循环执行
  19. setTimeout(() => {
  20. if (this.status === "pending") {
  21. this.status = "rejected";
  22. this.value = reason;
  23. if (this.rejectCallbackArr.length) this.rejectCallbackArr.forEach(item => item(this.value));
  24. }
  25. }, 0)
  26. }
  27. // 执行执行器函数(包含异常捕获)
  28. try {
  29. excutorCallBack && excutorCallBack(resolveFn, rejectFn);
  30. } catch (error) {
  31. rejectFn(error)
  32. }
  33. }
  34. // 实例方法
  35. then(resolveCallback, rejectCallback) {
  36. typeof resolveCallback !== "function" ? resolveCallback = result => result : null;
  37. typeof rejectCallback !== "function" ? rejectCallback = reason => {throw new Error(reason.message)} : null;
  38. return new MyPromise((resolve, reject) => {
  39. this.resolveCallbackArr.push(() => {
  40. try {
  41. let x = resolveCallback(this.value);
  42. x instanceof Promise ? x.then(resolve, reject) : resolve(x);
  43. }catch(err) {
  44. reject(err);
  45. }
  46. })
  47. this.rejectCallbackArr.push(() => {
  48. try{
  49. let x = rejectCallback(this.value);
  50. x instanceof Promise ? x.then(resolve, reject) : resolve(x);
  51. }catch(err) {
  52. reject(err);
  53. }
  54. })
  55. })
  56. }
  57. catch(rejectCallback) {
  58. return this.then(null, rejectCallback)
  59. }
  60. }
  61. export default MyPromise;