前言
百度了很多次别人写的promise ,也是一时兴起 今天自己写了一个并且做了这么一个记录
Promises/A+
同学们:此处自行查阅Promises/A+规范
Just do it
接下来我根据我自己习惯看规范
-
“promise” is an object or function with a then method whose behavior conforms to this specification.
菜?自己的翻译:class Promise{}和function Promise{} 都行,那我写的是class
class Promise{
constructor(execuctor) {}
}
export default Promise
复制代码
-
A promise must be in one of three states: pending, fulfilled, or rejected….
菜?自己的翻译:每个promise 都有三个状态 ,且pedding状态时可变更(通过resolve和reject) fulfilled, or rejected,但只支持变更一次,不能转变成任何其他状态。
-
“reason” is a value that indicates why a promise was rejected.
“value” is any legal JavaScript value (including undefined, a thenable, or a promise).
菜?自己的翻译: resolve() 和reject() 的参数 和其值的初始化,结合2做状态变更处理
//class 同级外层 定义状态的常量,等待使用,实际过程中为了可读性,通常都会定义常量
//状态常量
/**初始化状态*/
const PENDING = "PENDING";
/**成功状态*/
const FULFILLED = "FULFILLED";
/**失败状态*/
const REJECTED = "REJECTED";
class Promise{
constructor(execuctor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
const resolve = (val) => {
// 状态变更后 不可以在更改为其他状态,只支持修改一次
if (this.status === PENDING) {
this.value = val; //成功状态时 value的赋值
this.status = FULFILLED; //修改状态
}
};
const reject = (err) => {
// 状态变更后 不可以在更改为其他状态,只支持修改一次
if (this.status === PENDING) {
this.reason = err; //失败状态时的 reason的赋值
this.status = REJECTED; //修改状态
}
}
}
复制代码
-
“exception” is a value that is thrown using the throw statement.
菜?自己的翻译:throw 语句抛出的异常。这里按照我自己的理解 用try,catch 捕获异常的时候 调用reject(err)
try {
execuctor(resolve, reject);
} catch (err) {
reject(err);
}
复制代码
-
A promise’s then method accepts two arguments:
promise.then(onFulfilled, onRejected)….
菜?自己的翻译:then 方法的支持,FULFILLED执行onFulfilled,REJECTED执行onRejected而且参数均得是函数,这里规范我们没有全部粘贴
then(onFulfilled, onRejected) {
if (this.status === FULFILLED) {
onFulfilled(this.value);
}
if (this.status === REJECTED) {
onRejected(this.reason);
}
复制代码
完整代码
class Promise {
constructor(execuctor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
const resolve = (val) => {
// 状态变更后 不可以在更改为其他状态,只支持修改一次
if (this.status === PENDING) {
this.value = val; //成功状态时 value的赋值
this.status = FULFILLED; //修改状态
}
};
const reject = (err) => {
// 状态变更后 不可以在更改为其他状态,只支持修改一次
if (this.status === PENDING) {
this.reason = err; //失败状态时的 reason的赋值
this.status = REJECTED; //修改状态
}
};
try {
execuctor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
//then 的参数 resolve函数,和reject函数
if (this.status === FULFILLED) {
onFulfilled(this.value);
}
if (this.status === REJECTED) {
onRejected(this.reason);
}
}
}
export default Promise
复制代码
我们测试结果 测试插件用的是 code run (按照指南VS code插件分享之 — Run Code)
小结
到这里就写完了一个简易promise的全部代码,已经很晚了下次再写好了