简洁好懂的Promise实现(通过Promise A+规范测试)

42 阅读1分钟

原理

只有js代码,浅显易懂,只支持node环境,因为微任务调用node环境接口process.nextTick. 简单介绍一下Promsie类数据结构queue, onFulfilled, onRejected.

  • queue:存储当前promise调用then函数产生的新promise,存储在当前promise中,then函数可以多次调用,当当前promise的状态不为pending时从队列拿出then中的新promise用于回调执行.
  • onFulfilled: 存储then函数的onFulfilled回调,存储在then函数产生的新promise中,当当前promise的状态为fulfilled时,执行onFulfilled回调。
  • onRejected: 存储then函数的onRejected回调,存储在then函数产生的新promise中,当当前promise的状态为onRejected时,执行onRejected回调。

测试

Promise A+ 规范测试npm包 安装测试包

yarn global add promises-aplus-tests

执行测试

promises-aplus-tests promise.js

截屏2022-10-19 下午5.09.00.png