「这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战」。
1. 了解Promise A+
规范
Promise
的实现需要遵循Promise A+
的标准规范,这套规范告诉了我们该如何去实现一个符合标准的Promise
,下面是他的官网大家可以去看看。
Promise A+
官网 :promisesaplus.com/
2.实现Promise
的基本结构
- 首先我们回想一下,我们是如何使用一个
Promise
的。Promise
是一个类,我们需要使用new
关键字去调用它,new
一个Promise
的时候我们需要传递一个executor
执行函数,executor
函数有两个参数,分别是resolve
函数与reject
函数。Promise
有三个状态,默认是pending
状态(我们称其为等待状态),调用resolve
函数会使Promsie
的状态由pending
变为fulfilled
(我们称其为成功状态),调用reject
函数会使Promsie
的状态由pending
变为rejected
(我们称其为失败状态)。-
let p = new Promise((resolve, reject) => { resolve('成功') }) console.log(p);
- 控制台打印结果:
- 实现基本的
Promise
结构-
本次实现
Promise
的目录结构-
p.js
用来写我们的事例 -
promise
文件夹下index.js
中用来写我们promise
的实现,age.txt
与name.txt
是写事例需要用到的文本文件。
-
-
基本结构实现
- 我们用
class
来实现Promise
- 我们用变量定义三个状态分别是
PENDING、 FULFILLED、 REJECTED
,可以防止我们后续写字符串写错。 - 在
new Promise
的时候我们要传入executor
函数,executor
函数需要立即执行。 - 执行
executor
的时候我们需要传入resolve
函数与reject
函数 - 每个
Promise
还有三个属性,state
存放该Promise
的状态,value
存放Promise
成功的值,reason
存放Promise
失败的原因,最后我们将其导出,我们会在p.js
中导入,来使用它。
- 我们用
-
promise/index.js
const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class Promise{ constructor(executor){ this.state = PENDING this.value = undefined this.reason = undefined const resolve = (value) => { } const reject = (reason) => { } executor(resolve,reject) } then(onFulfilled, onRejected){ } } module.exports = Promise
-