资讯专栏INFORMATION COLUMN

手写一个PromiseA+的实现

suxier / 1496人阅读

摘要:手写一个的实现。当注册的回调函数返回的是的时候,从这个之后的所有的注册函数都应该注册在新返回的上。直到遇到下一个回调函数的返回值也是。

Promise

手写一个PromiseA+的实现。注意这里只是模拟,实际上原生的promise在事件队列中属于microTask。这里用setTimeout模拟不是特别恰当。因为setTimeout是一个macroTask。

1. 最简单的基本功能

</>复制代码

  1. /**
  2. * 定义Promise
  3. * 先实现一个最简单的。用setTimeout模拟一个异步的请求。
  4. */
  5. function Promise(fn){
  6. var value= null;
  7. var callbacks = [];
  8. this.then = function(onFulfilled) {
  9. callbacks.push(onFulfilled);
  10. }
  11. function resolve(value){
  12. callbacks.forEach(function(cb){
  13. cb(value);
  14. })
  15. }
  16. fn(resolve);
  17. }
  18. // 使用Promise
  19. var p = new Promise(function(resolve){
  20. setTimeout(function(){
  21. resolve("这是响应的数据")
  22. },2000)
  23. })
  24. p.then(function(response){
  25. console.log(response);
  26. })
2.链式调用

</>复制代码

  1. /**
  2. * 先看一下前一个例子存在的问题
  3. * 1.在前一个例子中不断调用then需要支持链式调用,每次执行then都要返回调用对象本身。
  4. * 2.在前一个例子中,当链式调用的时候,每次then中的值都是同一个值,这是有问题的。其实第一次then中的返回值,应该是第二次调用then中的函数的参数,依次类推。
  5. * 所以,我们进一步优化一下代码。
  6. *
  7. */
  8. function Promise(fn){
  9. var value= null;
  10. var callbacks = [];
  11. this.then = function(onFulfilled) {
  12. callbacks.push({f:onFulfilled});
  13. return this;
  14. }
  15. function resolve(value){
  16. callbacks.map(function(cb,index){
  17. if(index === 0){
  18. callbacks[index].value = value;
  19. }
  20. var rsp = cb.f(cb.value);
  21. if(typeof callbacks[index+1] !== "undefined"){
  22. callbacks[index+1].value = rsp;
  23. }
  24. })
  25. }
  26. fn(resolve);
  27. }
  28. // 使用Promise
  29. var p = new Promise(function(resolve){
  30. setTimeout(function(){
  31. resolve("这是响应的数据")
  32. },2000)
  33. })
  34. p.then(function(response){
  35. console.log(response);
  36. return 1;
  37. }).then(function(response){
  38. console.log(response);
  39. return 2;
  40. }).then(function(response){
  41. console.log(response);
  42. })
3. 异步

</>复制代码

  1. /**
  2. * 先看一下前一个例子存在的问题
  3. * 1. 如果在then方法注册回调之前,resolve函数就执行了,怎么办?比如 new Promise的时候传入的函数是同步函数的话,
  4. * then还没被注册,resolve就执行了。。这在PromiseA+规范中是不允许的,规范明确要求回调需要通过异步的方式执行。
  5. * 用来保证一致可靠的执行顺序。
  6. *
  7. * 因此我们需要加入一些处理。把resolve里的代码放到异步队列中去。这里我们利用setTimeout来实现。
  8. * 原理就是通过setTimeout机制,将resolve中执行回调的逻辑放置到JS任务队列末尾,以保证在resolve执行时,
  9. * then方法的回调函数已经注册完成
  10. *
  11. */
  12. function Promise(fn){
  13. var value= null;
  14. var callbacks = [];
  15. this.then = function(onFulfilled) {
  16. callbacks.push({f:onFulfilled});
  17. return this;
  18. }
  19. function resolve(value){
  20. setTimeout(function(){
  21. callbacks.map(function(cb,index){
  22. if(index === 0){
  23. callbacks[index].value = value;
  24. }
  25. var rsp = cb.f(cb.value);
  26. if(typeof callbacks[index+1] !== "undefined"){
  27. callbacks[index+1].value = rsp;
  28. }
  29. })
  30. },0)
  31. }
  32. fn(resolve);
  33. }
  34. // 使用Promise,现在即使是同步的立马resolve,也能正常运行了。
  35. var p = new Promise(function(resolve){
  36. resolve("这是响应的数据")
  37. })
  38. p.then(function(response){
  39. console.log(response);
  40. return 1;
  41. }).then(function(response){
  42. console.log(response);
  43. return 2;
  44. }).then(function(response){
  45. console.log(response);
  46. })
4. 状态机制

</>复制代码

  1. /**
  2. * 先看一下前一个例子存在的问题
  3. * 1.前一个例子还存在一些问题,如果Promise异步操作已经成功,在这之前注册的所有回调都会执行,
  4. * 但是在这之后再注册的回调函数就再也不执行了。具体的运行下面这段代码,可以看到“can i invoke”并没有打印出来
  5. * 想要解决这个问题,我们就需要加入状态机制了。具体实现看本文件夹下的另一个js文件里的代码。
  6. *
  7. */
  8. function Promise(fn){
  9. var value= null;
  10. var callbacks = [];
  11. this.then = function(onFulfilled) {
  12. callbacks.push({f:onFulfilled});
  13. return this;
  14. }
  15. function resolve(value){
  16. setTimeout(function(){
  17. callbacks.map(function(cb,index){
  18. if(index === 0){
  19. callbacks[index].value = value;
  20. }
  21. var rsp = cb.f(cb.value);
  22. if(typeof callbacks[index+1] !== "undefined"){
  23. callbacks[index+1].value = rsp;
  24. }
  25. })
  26. },0)
  27. }
  28. fn(resolve);
  29. }
  30. //
  31. var p = new Promise(function(resolve){
  32. resolve("这是响应的数据")
  33. })
  34. p.then(function(response){
  35. console.log(response);
  36. return 1;
  37. }).then(function(response){
  38. console.log(response);
  39. return 2;
  40. }).then(function(response){
  41. console.log(response);
  42. })
  43. setTimeout(function(){
  44. p.then(function(response){
  45. console.log("can i invoke?");
  46. })
  47. },0)

</>复制代码

  1. /**
  2. * 在promise01.js中,我们已经分析了,我们需要加入状态机制
  3. * 在这里实现一下PromiseA+中关于状态的规范。
  4. *
  5. * Promises/A+规范中的2.1Promise States中明确规定了,pending可以转化为fulfilled或rejected并且只能转化一次,
  6. * 也就是说如果pending转化到fulfilled状态,那么就不能再转化到rejected。
  7. * 并且fulfilled和rejected状态只能由pending转化而来,两者之间不能互相转换
  8. *
  9. */
  10. function Promise(fn){
  11. var status = "pending"
  12. var value= null;
  13. var callbacks = [];
  14. this.then = function(onFulfilled) {
  15. // 如果是pending状态,则加入到注册队列中去。
  16. if(status === "pending"){
  17. callbacks.push({f:onFulfilled});
  18. return this;
  19. }
  20. // 如果是fulfilled 状态,此时直接执行传入的注册函数即可。
  21. onFulfilled(value);
  22. return this;
  23. }
  24. function resolve(newValue){
  25. value = newValue;
  26. status = "fulfilled";
  27. setTimeout(function(){
  28. callbacks.map(function(cb,index){
  29. if(index === 0){
  30. callbacks[index].value = newValue;
  31. }
  32. var rsp = cb.f(cb.value);
  33. if(typeof callbacks[index+1] !== "undefined"){
  34. callbacks[index+1].value = rsp;
  35. }
  36. })
  37. },0)
  38. }
  39. fn(resolve);
  40. }
  41. //
  42. var p = new Promise(function(resolve){
  43. resolve("这是响应的数据")
  44. })
  45. p.then(function(response){
  46. console.log(response);
  47. return 1;
  48. }).then(function(response){
  49. console.log(response);
  50. return 2;
  51. }).then(function(response){
  52. console.log(response);
  53. })
  54. setTimeout(function(){
  55. p.then(function(response){
  56. console.log("can i invoke?");
  57. })
  58. },1000)

</>复制代码

  1. /**
  2. * 刚才的例子中,确实打印出了 can i invoke,但是之前then的注册函数的返回值,并没有打印出来。
  3. * 也就是说 1 和 2 并没有被打印出来,看下面的注释
  4. *
  5. */
  6. function Promise(fn){
  7. var status = "pending"
  8. var value= null;
  9. var callbacks = [];
  10. this.then = function(onFulfilled) {
  11. if(status === "pending"){
  12. callbacks.push({f:onFulfilled});
  13. return this;
  14. }
  15. onFulfilled(value);
  16. return this;
  17. }
  18. function resolve(newValue){
  19. value = newValue;
  20. status = "fulfilled";
  21. setTimeout(function(){
  22. callbacks.map(function(cb,index){
  23. if(index === 0){
  24. callbacks[index].value = newValue;
  25. }
  26. var rsp = cb.f(cb.value);
  27. if(typeof callbacks[index+1] !== "undefined"){
  28. callbacks[index+1].value = rsp;
  29. }
  30. })
  31. },0)
  32. }
  33. fn(resolve);
  34. }
  35. var p = new Promise(function(resolve){
  36. resolve("aaaaaa")
  37. })
  38. p.then(function(response){
  39. console.log(response);
  40. return 1;
  41. }).then(function(response){
  42. console.log(response); // 这里应该打印的是45行返回的1,但是打印出来的确是aaaaaa
  43. return 2;
  44. }).then(function(response){
  45. console.log(response); // 这里应该打印的是48行返回的2,但是打印出来的确是aaaaaa
  46. })
  47. setTimeout(function(){
  48. p.then(function(response){
  49. console.log("can i invoke?");
  50. })
  51. },1000)
  52. /**
  53. * 问题的根源在于什么呢?
  54. * 问题的根源是每次的then的返回值都是p,当状态是fulfilled,执行的是onFulfilled(value)
  55. * 此处的value是p的value,也就是fulfilled状态的value。根据规范,promise应该是只能发射单值。
  56. * 而我们设计了一个callback堆栈中有一系列的值。生生的把promise变成了多值发射。
  57. *
  58. * 所以,调整思路,每个then都应该返回一个promise,这个promise应该是一个全新的promise。
  59. * 具体实现见下一个例子。
  60. */

</>复制代码

  1. /**
  2. * 根据刚才的分析,我们重新优化一下代码
  3. * 1.去掉之前的多值设计
  4. * 2.每次的then 返回的都是一个全新的promise
  5. *
  6. */
  7. function Promise(fn){
  8. var status = "pending"
  9. var value= null;
  10. var callbacks = [];
  11. var self = this;
  12. this.then = function(onFulfilled) {
  13. return new Promise(function(resolve){
  14. function handle(value){
  15. var res = typeof onFulfilled === "function" ? onFulfilled(value) : value;
  16. resolve(res);
  17. }
  18. // 如果是pending状态,则加入到注册队列中去。
  19. if(status === "pending"){
  20. callbacks.push(handle);
  21. // 如果是fulfilled 状态。
  22. }else if(status === "fulfilled"){
  23. handle(value);
  24. }
  25. })
  26. }
  27. function resolve(newValue){
  28. value = newValue;
  29. status = "fulfilled";
  30. setTimeout(function(){
  31. callbacks.map(function(cb){
  32. cb(value);
  33. })
  34. },0)
  35. };
  36. fn(resolve);
  37. }
  38. //
  39. var p = new Promise(function(resolve){
  40. resolve("这是响应的数据")
  41. })
  42. p.then(function(response){
  43. console.log(response);
  44. return 1;
  45. }).then(function(response){
  46. console.log(response);
  47. return 2;
  48. }).then(function(response){
  49. console.log(response);
  50. })
  51. setTimeout(function(){
  52. p.then(function(response){
  53. console.log("can i invoke?");
  54. })
  55. },1000)
  56. /**
  57. * 运行一下,完美输出
  58. * 先是输出“这是响应的数据”,然后是“1”,然后是“2”, 然后是“can i invoke?”
  59. *
  60. * 接下来我们要好好整理一下代码了。把一些公用的方法放到构造函数的原型上去。改造之后的例子见下一个例子
  61. */

</>复制代码

  1. /**
  2. * 根据刚才的分析,我们重新优化一下代码
  3. * 1.把私有属性挂到实例上去
  4. * 2.把公共方法挂到构造函数的原型上去
  5. *
  6. */
  7. function Promise(fn){
  8. this.status = "pending";
  9. this.value= null;
  10. this.callbacks = [];
  11. var self = this;
  12. function resolve(newValue){
  13. self.value = newValue;
  14. self.status = "fulfilled";
  15. setTimeout(function(){
  16. self.callbacks.map(function(cb){
  17. cb(value);
  18. })
  19. },0)
  20. }
  21. fn(resolve);
  22. }
  23. Promise.prototype = Object.create(null);
  24. Promise.prototype.constructor = Promise;
  25. Promise.prototype.then = function(onFulfilled){
  26. var self = this;
  27. return new Promise(function(resolve){
  28. function handle(value){
  29. var res = typeof onFulfilled === "function"? onFulfilled(value) : value;
  30. resolve(res);
  31. }
  32. if(self.status==="pending"){
  33. self.callbacks.push(handle);
  34. }else if(self.status ==="fulfilled"){
  35. handle(self.value);
  36. }
  37. })
  38. }
  39. // 使用
  40. var p = new Promise(function(resolve){
  41. resolve("这是响应的数据")
  42. })
  43. p.then(function(response){
  44. console.log(response);
  45. return 1;
  46. }).then(function(response){
  47. console.log(response);
  48. return 2;
  49. }).then(function(response){
  50. console.log(response);
  51. })
  52. setTimeout(function(){
  53. p.then(function(response){
  54. console.log("can i invoke?");
  55. })
  56. },1000)
5.处理注册的函数返回值是promise的情况

</>复制代码

  1. /**
  2. * 不出意料,又要抛出问题了。当then注册的回调函数返回的是promise的时候,从这个then之后的所有then的注册函数
  3. * 都应该注册在新返回的promise上。直到遇到下一个回调函数的返回值也是promise。
  4. *
  5. * 实现思路:
  6. * 在handle中判断注册函数返回的是否是promise。如果是的话,则resolve这个返回的promise的值,具体代码看一下36到38行
  7. *
  8. */
  9. function Promise(fn){
  10. this.status = "pending";
  11. this.value= null;
  12. this.callbacks = [];
  13. var self = this;
  14. function resolve(newValue){
  15. self.value = newValue;
  16. self.status = "fulfilled";
  17. setTimeout(function(){
  18. self.callbacks.map(function(cb){
  19. cb(value);
  20. })
  21. },0)
  22. }
  23. fn(resolve);
  24. }
  25. Promise.prototype = Object.create(null);
  26. Promise.prototype.constructor = Promise;
  27. Promise.prototype.then = function(onFulfilled){
  28. var self = this;
  29. var promise = new Promise(function(resolve){
  30. function handle(value){
  31. var res = typeof onFulfilled === "function"? onFulfilled(value) : value;
  32. if(res instanceof Promise){
  33. promise = res;
  34. resolve(res.value);
  35. }else {
  36. resolve(res);
  37. }
  38. }
  39. if(self.status==="pending"){
  40. self.callbacks.push(handle);
  41. }else if(self.status ==="fulfilled"){
  42. handle(self.value);
  43. }
  44. })
  45. return promise;
  46. }
  47. // 使用
  48. var p = new Promise(function(resolve){
  49. resolve("这是响应的数据")
  50. })
  51. p.then(function(response){
  52. console.log(response);
  53. return new Promise(function(resolve){
  54. resolve("testtest")
  55. })
  56. }).then(function(response){
  57. console.log(response);
  58. return 2;
  59. }).then(function(response){
  60. console.log(response);
  61. })
  62. setTimeout(function(){
  63. p.then(function(response){
  64. console.log("can i invoke?");
  65. return new Promise(function(resolve){
  66. resolve("hhhhhh")
  67. })
  68. }).then(function(response){
  69. console.log(response);
  70. })
  71. },1000)

源码全部在github上:https://github.com/JesseZhao1...

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

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

相关文章

  • 啥?喝着阔落吃着西瓜就把Promise手写出来了???

    摘要:嗝首先,我们通过字面可以看出来是一种解决方案,而且还有两种传统的解决方案回调函数和事件,,那么我们就来先聊聊这两种方案。 前言 虽然今年已经18年,但是今天还是要继续聊聊ES6的东西,ES6已经过去几年,可是我们对于ES6的语法究竟是掌握了什么程度,是了解?会用?还是精通?相信大家和我一样都对自己有着一个提升的心,对于新玩具可不能仅仅了解,对于其中的思想才是最吸引人的,所以接下来会通过...

    idisfkj 评论0 收藏0
  • 一步一步实现一个符合PromiseA+规范Promise库(1)

    摘要:今天我们来自己手写一个符合规范的库。是异步编程的一种解决方案,比传统的解决方案回调函数和事件更合理和更强大。我们可以看到,其实就是一个构造函数。所以说我们的数组里存的是一个一个的的回调函数,也就是一个一个。 今天我们来自己手写一个符合PromiseA+规范的Promise库。大家是不是很激动呢?? showImg(https://segmentfault.com/img/bV6t4Z?...

    joyvw 评论0 收藏0
  • Promise源码实现(完美符合Promise/A+规范)

    摘要:以上代码,可以完美通过所有用例。在的函数中,为何需要这个同样是因为规范中明确表示因此我们需要这样的来确保只会执行一次。其他情况,直接返回以该值为成功状态的对象。 Promise是前端面试中的高频问题,我作为面试官的时候,问Promise的概率超过90%,据我所知,大多数公司,都会问一些关于Promise的问题。如果你能根据PromiseA+的规范,写出符合规范的源码,那么我想,对于面试...

    gaomysion 评论0 收藏0
  • Promise 详解

    摘要:被观察者管理内部和的状态转变,同时通过构造函数中传递的和方法以主动触发状态转变和通知观察者。第一个回调函数是对象的状态变为时调用,第二个回调函数是对象的状态变为时调用可选实现主要实现第一步,初步构建。 Promise 含义 Promise是异步编程的一种解决方案,比传统的解决方案(回调函数和事件)更合合理、强大。所谓Promise,简单来说就是一个容器,里面保存着某个未来才会结束的事件...

    anquan 评论0 收藏0
  • Promise 简单实现

    摘要:简单实现前言你可能知道,的任务执行的模式有两种同步和异步。你已经实现了方法方法是一个很好用的方法。感兴趣的朋友可以自行去研究哈附上代码完整的实现个人博客链接 Promise 简单实现 前言 你可能知道,javascript 的任务执行的模式有两种:同步和异步。 异步模式非常重要,在浏览器端,耗时很长的操作(例如 ajax 请求)都应该异步执行,避免浏览器失去响应。 在异步模式编程中,我...

    dayday_up 评论0 收藏0

发表评论

0条评论

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