资讯专栏INFORMATION COLUMN

自己如何实现promise?

kycool / 838人阅读

摘要:如果让你实现一个你会怎么做自己实现的大体思路我们要明确我们需要一个异步的操作方法满足异步回调。所以选择加入作为实现的基础,让函数实现延迟触发。测试代码测试第二版实现返回一个触发返回一个触发

如果让你实现一个 promise ,你会怎么做?

自己实现promise的大体思路

我们要明确我们需要一个异步的操作方法,满足异步回调。所以选择加入setTimeout 作为实现的基础, 让函数实现延迟触发。

保持一个原则,控制 promise 改变状态的只有 promise 构造函数里的 reslove 、 reject 函数。

链式调用的原理, 类似jQuery,它会在调用方法后, return this. 从而形成链式调用。所以我们采用在调用then(fn)、 catch(fn) 后 会返回一个新的 promise 对象, 然而 这个 promise 对象 受到 它的上级promise 对象的状态结果 和 fn 运行结果的控制。

知识点:
里面 应该 用到点 js 作用域 、 函数闭包、 继承 、 上下文 绑定知识、引用传递。

存在问题

cbList、rhList、 cs 这个三个, Promise 对象能直接访问, 如果对其直接操作可能造成 程序紊乱。

代码如有纰漏,望大家指正

</>复制代码

  1. var JcPromise = function (fn) {
  2. // 防止 用户 直接 更改 state
  3. var state = "wait"
  4. // state 为 resolve 状态, 回调函数数组
  5. var cbList = []
  6. // state 为 reject 状态, 回调函数数组
  7. var rjList = []
  8. this.cbList = cbList
  9. this.rjList = rjList
  10. //
  11. this.cs = undefined
  12. // 获取 promise 的状态
  13. this.getState = function () {
  14. return state
  15. }
  16. /* 函数闭包,函数 定义在里面, 防止 外面用户 直接 使用 resolve 和 reject; */
  17. // Promise成功触发 函数
  18. var reslove = function (data) {
  19. this.cs = data
  20. if (state !== "wait") {
  21. return
  22. } else {
  23. state = "solve"
  24. while (this.cbList.length) {
  25. cbList.shift()(data)
  26. }
  27. }
  28. }
  29. // Promise 拒绝 触发函数
  30. var reject = function (e) {
  31. this.cs = e
  32. if (state !== "wait") {
  33. return
  34. } else {
  35. state = "reject"
  36. while (rjList.length) {
  37. rjList.shift()(e)
  38. }
  39. }
  40. }
  41. // 绑定函数 conext 及 this 为当前 promise对象
  42. reslove = reslove.bind(this)
  43. reject = reject.bind(this)
  44. // 延迟 触发
  45. setTimeout(function () {
  46. fn(reslove, reject)
  47. }, 0)
  48. }
  49. JcPromise.prototype.then = function (fn) {
  50. var handleObj = {}
  51. var nextPromise = new JcPromise(function (r, j) {
  52. handleObj.r = r
  53. handleObj.j = j
  54. })
  55. var fixFn = function (data) {
  56. var result = null
  57. try {
  58. result = fn(data)
  59. // 判断result是不是 JcPromise实例。
  60. if (result instanceof JcPromise) {
  61. result.then(function (data) {
  62. handleObj.r(data)
  63. }).catch(function (e) {
  64. handleObj.j(e)
  65. })
  66. } else {
  67. handleObj.r(result)
  68. }
  69. } catch (e){
  70. handleObj.j(e)
  71. }
  72. }
  73. //判断当前状态 如果 是 solve 直接 运行, 如果不是,酒吧 fixFn 推入 cbList 数组。
  74. if (this.getState() === "solve") {
  75. setTimeout(function () {
  76. fixFn(this.cs)
  77. }, 0)
  78. } else {
  79. this.cbList.push(fixFn)
  80. }
  81. return nextPromise
  82. }
  83. JcPromise.prototype.catch = function (fn) {
  84. var handleObj = {}
  85. var nextPromise = new JcPromise(function (r, j) {
  86. handleObj.r = r
  87. handleObj.j = j
  88. })
  89. var fixFn = function (e) {
  90. var result = null
  91. try {
  92. result = fn(e)
  93. if (result instanceof JcPromise) {
  94. result.then(function (data) {
  95. handleObj.r(data)
  96. }).catch(function (e) {
  97. handleObj.j(e)
  98. })
  99. } else {
  100. handleObj.r(result)
  101. }
  102. } catch (e){
  103. handleObj.j(e)
  104. }
  105. }
  106. if (this.getState() === "reject") {
  107. setTimeout(function () {
  108. fixFn(this.cs)
  109. }, 0)
  110. } else {
  111. this.rjList.push(fixFn)
  112. }
  113. return nextPromise
  114. }

</>复制代码

  1. // 测试代码
  2. var p = new JcPromise(function(r, j) {
  3. setTimeout(function() {r(100)}, 3000)
  4. }).then(data => {
  5. console.log("1", data)
  6. return new JcPromise((r, j) => {
  7. setTimeout(() => {
  8. r("hi")
  9. }, 3000)
  10. })
  11. }).then(data => console.log("2", data)).then(function () {
  12. console.log("xxx", xx + 1)
  13. }).catch(e => console.log(e)).then(data => console.log(data, "end"))

demo 测试
第二版 jcPromise 实现

</>复制代码

  1. var JcPromise = (function() {
  2. function JcPromise(fn) {
  3. fn = fn || noop;
  4. var statusList = ["start", "pending", "succeed", "err"];
  5. var cbStatus = [0, 1];
  6. var status = statusList[0];
  7. var data = null;
  8. var err = null;
  9. var that = this;
  10. var successFn = [];
  11. var errFn = [];
  12. function resolve(d) {
  13. data = d;
  14. that._changeStatus(2);
  15. };
  16. function reject(e) {
  17. err = e;
  18. that._changeStatus(3);
  19. };
  20. this.getData = function() {
  21. return data;
  22. };
  23. this.getErr = function() {
  24. return err
  25. };
  26. this.getStatus = function() {
  27. return status
  28. };
  29. this._changeStatus = function(idx) {
  30. switch (status) {
  31. case statusList[2]:
  32. case statusList[3]:
  33. {
  34. return false
  35. }
  36. };
  37. status = statusList[idx];
  38. if (status === statusList[3]) {
  39. setTimeout(function() {
  40. that._triggerCatch();
  41. }, 0)
  42. }
  43. if (status === statusList[2]) {
  44. setTimeout(function() {
  45. that._triggerThen();
  46. }, 0)
  47. }
  48. };
  49. this._pushThenCb = function(cb) {
  50. successFn.push({
  51. status: cbStatus[0],
  52. cb: cb
  53. });
  54. if (status === statusList[2]) {
  55. this._triggerThen();
  56. }
  57. };
  58. this._pushCatchCb = function(cb) {
  59. errFn.push({
  60. status: cbStatus[0],
  61. cb: cb
  62. });
  63. if (status === statusList[3]) {
  64. this._triggerCatch();
  65. }
  66. };
  67. this._triggerThen = function() {
  68. successFn.map(function(item) {
  69. if (item.status === cbStatus[0]) {
  70. item.cb(data);
  71. item.status = cbStatus[1];
  72. }
  73. })
  74. };
  75. this._triggerCatch = function() {
  76. errFn.map(function(item) {
  77. if (item.status === cbStatus[0]) {
  78. item.cb(err);
  79. item.status = cbStatus[1];
  80. }
  81. })
  82. };
  83. this._changeStatus(1);
  84. this.uuid = uuid++;
  85. try {
  86. fn(resolve, reject);
  87. } catch (e) {
  88. reject(e)
  89. }
  90. return this
  91. };
  92. JcPromise.fn = JcPromise.prototype;
  93. // 返回一个promise
  94. JcPromise.fn.then = function(cb) {
  95. var promiseR = null;
  96. var promiseJ = null;
  97. var result = null;
  98. var that = this;
  99. var fn = function() {
  100. setTimeout(function() {
  101. try {
  102. var data = that.getData();
  103. result = cb(data);
  104. if (typeof result === "object" && result !== null && result.constructor === JcPromise) {
  105. result.then(function(data) {
  106. promiseR(data)
  107. }).catch(function(e) {
  108. promiseJ(e)
  109. })
  110. } else {
  111. promiseR(result)
  112. }
  113. } catch (e) {
  114. promiseJ(e)
  115. }
  116. }, 0);
  117. };
  118. this._pushThenCb(fn);
  119. // 触发promise
  120. return new JcPromise(function(r, j) {
  121. promiseR = r;
  122. promiseJ = j;
  123. });
  124. };
  125. // 返回一个promise
  126. JcPromise.fn.catch = function(cb) {
  127. var promiseR = null;
  128. var promiseJ = null;
  129. var result = null;
  130. var that = this;
  131. var fn = function() {
  132. setTimeout(function() {
  133. try {
  134. var data = that.getErr();
  135. result = cb(data);
  136. if (typeof result === "object" && result !== null && result.constructor === JcPromise) {
  137. result.then(function(data) {
  138. promiseR(data)
  139. }).catch(function(e) {
  140. promiseJ(e)
  141. })
  142. } else {
  143. promiseR(result)
  144. }
  145. } catch (e) {
  146. promiseJ(e)
  147. }
  148. }, 0)
  149. };
  150. this._pushCatchCb(fn);
  151. // 触发promise
  152. return new JcPromise(function(r, j) {
  153. promiseR = r;
  154. promiseJ = j;
  155. });
  156. };
  157. return JcPromise
  158. })();

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/93453.html

相关文章

  • JavaScript 异步

    摘要:从最开始的到封装后的都在试图解决异步编程过程中的问题。为了让编程更美好,我们就需要引入来降低异步编程的复杂性。写一个符合规范并可配合使用的写一个符合规范并可配合使用的理解的工作原理采用回调函数来处理异步编程。 JavaScript怎么使用循环代替(异步)递归 问题描述 在开发过程中,遇到一个需求:在系统初始化时通过http获取一个第三方服务器端的列表,第三方服务器提供了一个接口,可通过...

    tuniutech 评论0 收藏0
  • 高级前端面试题大汇总(只有试题,没有答案)

    摘要:面试题来源于网络,看一下高级前端的面试题,可以知道自己和高级前端的差距。 面试题来源于网络,看一下高级前端的面试题,可以知道自己和高级前端的差距。有些面试题会重复。 使用过的koa2中间件 koa-body原理 介绍自己写过的中间件 有没有涉及到Cluster 介绍pm2 master挂了的话pm2怎么处理 如何和MySQL进行通信 React声明周期及自己的理解 如何...

    kviccn 评论0 收藏0
  • 2018大厂高级前端面试题汇总

    摘要:面试的公司分别是阿里网易滴滴今日头条有赞挖财沪江饿了么携程喜马拉雅兑吧微医寺库宝宝树海康威视蘑菇街酷家乐百分点和海风教育。 (关注福利,关注本公众号回复[资料]领取优质前端视频,包括Vue、React、Node源码和实战、面试指导) 本人于7-8月开始准备面试,过五关斩六将,最终抱得网易归,深深感受到高级前端面试的套路。以下是自己整理的面试题汇总,不敢藏私,统统贡献出来。 面试的公司分...

    zzir 评论0 收藏0

发表评论

0条评论

kycool

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<